Pass Additional ViewData to an ASP.NET MVC 4 Partial View While Propagating ModelState Errors

ASP.NET MVC 4

In my ASP.NET MVC 4 partial view, I was having an issue where VaidationSummary and VaidationMessageFor were coming up blank. I scratched my head on this for quite some time. I finally came across this entry at the MVC forums at MSDN. It turns out I wasn’t passing the ViewData from parent view, but in fact my own fresh ViewData. This is how I had things before:

The Wrong Way

@{
    Html.RenderPartial("_CreateEditDisplay", Model, new ViewDataDictionary { { "Submit", true }, { "Action", "Edit" }, { "ReadOnly", false } });
}

The Right Way

I figured it out by doing this instead:

@{
    Html.ViewData.Add(new KeyValuePair<string, object>("Submit", true));
    Html.ViewData.Add(new KeyValuePair<string, object>("Action", "Edit"));
    Html.ViewData.Add(new KeyValuePair<string, object>("ReadOnly", false));

    Html.RenderPartial("_CreateEditDisplay", Model, Html.ViewData);
}

Basically what we have here is the original ViewData from the parent view with my additional add-ons that are passed to the partial view. Once I made this change, the ModelState is propagated to the partial view and VaidationSummary and VaidationMessageFor are outputting the desired results.

4 comments

  1. It is still wrong approach. Won’t solve anything. I don’t know why Html helpers don’t work here but the workaround is just add things to ViewData already in the controller’s action.

  2. This will work instead (note the constructor argument):

    new ViewDataDictionary(ViewData) { { “Submit”, true }, { “Action”, “Edit” }, { “ReadOnly”, false } });

Comments are closed.