I’m new to MVC 3 and I have the following views:
Index:
@using (Html.BeginForm())
{
@Html.Hidden("id", "1")
<input type="submit" value="Submit" />
}
Main:
@using (Html.BeginForm())
{
@Html.Hidden("id", "2")
<input type="submit" value="Save" />
}
And the following Controller:
public ActionResult Index()
{
ViewBag.Message = "Welcome!";
return View();
}
[HttpPost]
public ActionResult Index(string id)
{
if ("1".Equals(id))
{
return View("Main");
}
else("2".Equals(id))
{
return View();
}
}
My expectation would be that the Main view would render the hidden input with a value of “2”. However, upon reaching the Main page, and inspecting the source, the value is still being set to “1”. Any idea what I’m doing wrong here?
That depends on the URL you are using. If you are entering
..../Index, then it will go to the Index view, but if you are going to.../Index/1then it will go to the Main view and render your two (which is kind of odd because a 1 goes to 2 :))Also, you will only hit the
Index(string id)method on aPOST, so that might also be your problem. a typical URL request comes across as aGETIf that does not help, then you might need to provide more details (what URL you are attempting to hit, and how you are trying to get there)
UPDATE AFTER TRYING THIS MYSELF
I see what you are saying. The reason for the hidden field being set to 1 is because the ModelState plugs it in for you. As far as I can tell, this should NOT happen since you are explicitly setting the value. However, it appears that if there is a matching state item, it will use that instead. You can test this by changing from using
idto anything else in your Main’s hidden input name.Here is the documentation. In the remarks, it does state that this is meant more for model binding, but I would have thought that the value inserted would override anything else.
FINAL UPDATE
It turns out that this actually has already been brought up to the appropriate person, and it is by design. They SHOULD change the documentation to make this more explicit, though. Here is the SO question that answers this