Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem showing modelstate errors while using RenderPartialToString

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());
like image 424
Martin at Mennt Avatar asked Sep 17 '26 19:09

Martin at Mennt


1 Answers

After spending too much time on this problem I saw that the ModelState items shouldn't be added to the viewContext.Controller.ViewData.ModelState, it should be added to viewContext.ViewData.ModelState. After making this change the ModelState errors were being rendered.

like image 173
BarryC Avatar answered Sep 19 '26 19:09

BarryC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!