1
Vote

View rendering to string fails (it was working in MVC3)

description

When you use a complex hierarchic Model like :
Model
+--InvoiceHeader
| +-- Address Sender
| +-- Address Recipient
+--List<DetailRow>
       +-- DetailRow
I build
View Invoice
+--InvoiceHeader_TemplateEditor
| +-- Address_TemplateEditor
| +-- Address_TemplateEditor
+--List<DetailRow>
       +-- DetailRow_TemplateEditor
To update keeping the MVC spirit, I also build some partial view for me to rebuild server side hierarchy like that :

_Adress_Updater
+--Address_TemplateEditor

So, if I update Address server side and I regenerate view as string, MVC will automatically generate name and id hierarchy as in the first call, then, I just have to update the div I want to update with de string partial view rendered server side and transfered client side in a JSon Data Bag.

This technique was working in MVC 3 now it fails in MVC 4.

There is multiple RenderViewToString on the internet I tested all, same result.

I also make an other try :

I rendered the partial view but I replaced a textarea generated by @Html.Textareafor(m => m.MyField) by
<div> @Model.MyField </div> It works.

I fell the problem seems to have static variables not reinitialized or something like that.

If you want, you can add me to the contributors, I could try to understand and fix the bug because it's very important for my open source framework.

Awating your reaction,

Best regards

Laurent

comments

LaurentJordi wrote Jul 29, 2012 at 12:58 PM

The method is RenderPartialViewToString
    protected string RenderPartialViewToString(string viewName, object model)
    {
        string toReturn;
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            toReturn = sw.GetStringBuilder().ToString();
            //toReturn = RenderView(viewContext);
            return toReturn;

        }
    }

LaurentJordi wrote Aug 28, 2012 at 5:42 PM

The Lorenz Cuno Klopfenstein works because he creates a Fake Context.

http://www.klopfenstein.net/lorenz.aspx/render-partial-view-to-string-in-asp-net-mvc

Even if his extension method works, I still consider it's a Bug (MVC3.1 and 4).

Best regards,

Laurent