Search code examples
asp.net-mvcviewdatahidden-field

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


<%: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?


Solution

  • 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.