MVC3 Razor - how to pass data from controller to view - and back to controller
I have a view where everything will be populated by the user but refers to the parent. I am passing this ID to my View using the ViewBag, but I have no idea how to get it back to a message in the controller. I've tried hidden form fields, but it doesn't show up in the message, or I don't know how to grab it ... Controller:
public ActionResult AddCar(int id)
{
ViewBag.Id = id;
return View();
}
View (try):
@using (Html.BeginForm("AddReturn", "DealerAdmin", new { id = carId }))
{
View (tried):
@Html.Hidden(carId.ToString())
HOw am I retrieving the value in my post in my controller? Or is there a better / different way to approach it? THANKS TO
source to share
Create a ViewModel for the post, it will be like this
public class Post
{
int id {get;set;}
//other properties
}
and in your controller action send the post object
public ActionResult AddCar(int id)
{
Post post = new Post();
post.Id = id;
return View(post);
}
your view should use the Post class as a model
@model namespace.Post
@using (Html.BeginForm("AddReturn", "DealerAdmin", FormMethod.Post)
{
@Html.HiddenFor(model => model.Id)
}
and your controller action that expects a result must have a post object as an input parameter
public ActionResult AddReturn(Post post)
{
//your code
}
source to share
there is some way
1.post the value using query string if there is only one value to send to controller
2.if you want to collect many fields from view you can use formcollection
sample ::
public actionresult method1()
{
int id = //everything you want
viewbag.id=id;
....
//and other field to collect
}
in sight
<form method="post" action="method1" enctype="now i dont remeber the value of this option" >
@html.hidden("id")
.....
<input type="submit" value"Send"/>
</form>
[httpPost]
public actionresult method1(fromcollection collection)
{
int id = collection.get("id");
....
//and other field to collect
}
source to share