How do I get ViewData inside a form to display correctly?

1.5k views Asked by At
<%:ViewData["galleryId"]%>
<% using (Html.BeginForm(
             "FinishEdit" , 
             "GalleryManager" , 
             FormMethod.Post , 
             new { enctype = "multipart/form-data" }
             )
         ) 
   {%>
    <%:Html.Hidden("galleryId" , ViewData["galleryId"])%>
<% } %>

The view data outside of the form renders correctly, but the viewdata inside the form does not. What is going on?

2

There are 2 answers

0
Darin Dimitrov On BEST ANSWER

Try clearing the model state in your controller action if you intend to modify any of the POSTed variables and render the same view:

[HttpPost]
public ActionResult FinishEdit()
{
    ...
    ModelState.Remove("galleryId");
    ViewData["galleryId"] = "some new gallery id";
    return View();
}

Html helpers are first looking in the model state dictionary values before ViewData and Model.

0
Alexander Prokofyev On

Html.Hidden helper looks first ModelState dictionary. This could be a reason.