Reputation: 1610
I have a view where everything will be populated by the user - but relates to a parent entity. I pass that Id to my view using ViewBag, but I don't know how to get it back to the post action in the controller. I have tried hidden form fields, but it isn't showing in the post, or I do not know how to grab it... Controller:
public ActionResult AddCar(int id)
{
ViewBag.Id = id;
return View();
}
View (tried):
@using (Html.BeginForm("AddReturn", "DealerAdmin", new { id = carId }))
{
View (tried):
@Html.Hidden(carId.ToString())
HOw do I retrieve the value in my post action in my controller? Or is there a better/different way to approach it? THanks
Upvotes: 3
Views: 16443
Reputation: 4915
The hidden field should works. The problem is that your controller did not accept it.
You can use ViewModel to achieve this. Or, use the code below in your action:
id = Request.Form["id"]
Upvotes: 2
Reputation: 1443
there some way
1. send the value with query string if there is only one value to send to the controller
2. if you want collect many field from view you can use formcollection
sample::
public actionresult method1()
{
int id = //everything you want
viewbag.id=id;
....
//and other field to collect
}
in view
<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
}
Upvotes: 0
Reputation: 887
Create a ViewModel for post, it would be as follows
public class Post
{
int id {get;set;}
//other properties
}
and in your controller action send a 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 the model
@model namespace.Post
@using (Html.BeginForm("AddReturn", "DealerAdmin", FormMethod.Post)
{
@Html.HiddenFor(model => model.Id)
}
and your controller action which expects result should have a post object as the input parameter
public ActionResult AddReturn(Post post)
{
//your code
}
Upvotes: 9
Reputation: 1038710
Try like this:
@using (Html.BeginForm("AddReturn", "DealerAdmin", new { id = ViewBag.Id }))
{
...
}
Upvotes: 0