views:

187

answers:

2

Im using the following code:

public string RenderPartialToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
    {
        ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName);

        if (result.View != null)
        {
            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            {
                using (HtmlTextWriter output = new HtmlTextWriter(sw))
                {
                    ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);
                    result.View.Render(viewContext, output);
                }
            }

            return sb.ToString();
        }

        return String.Empty;
    }

To return a partial view and a form through JSON. It works as it should, but as soon as I get modelstate errors my ValidationSummary does not show. The JSON only return the default form but it does not highlight the validation errors or show the validation summary.

Am I missing something?

This is how I call the RenderPartialToString:

string partialView = RenderPartialToString(this.ControllerContext, "~/Areas/User/Views/Account/ChangeAccountDetails.ascx", new ViewDataDictionary(avd), new TempDataDictionary());
+2  A: 

I had the same issue with a similar code:

All fix when added this lines:

// copy model state items to the html helper
                foreach (var item in context.Controller.ViewData.ModelState)
                    html.ViewData.ModelState.Add(item);

If i do a port to this particular scenario it ll be something like

    ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);

//Copy the ModelSate            
    foreach (var item in context.Controller.ViewData.ModelState)
    viewContext.Controller.ViewData.ModelState.Add(item);

result.View.Render(viewContext, output);
Omar
Thank you, I will test this code later today :D
Martin
Okay, I have tested the code, I think i'm missing something, I got this error:`An item with the same key has already been added.`
Martin
mmm.. weird the original problem resides in ViewData as it does not contain the ModelStateDictionary, try to inspect the viewData at this line "ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);" with a breakpoint, it should be empty, thats why i added the foreach that fill the ModelState of the new ViewContext.
Omar
Okay, im not sure how this can be of any help. But when I added { } around ModelState.Add it all worked.
Martin
A: 

This is what I did to make it work:

foreach (var item in context.Controller.ViewData.ModelState)
{
    viewContext.Controller.ViewData.ModelState.Add(item);
}

Not sure why I needed the { } 's..

Martin