简体   繁体   中英

How to Render Partial View To String

I tried to convert Umbraco Children item into a PartialView but i want it to return as a string and not as a partial View.

I read a lot in the forums and i've got errors when i'm trying these examples.

I have few different templates which i want to get from the controller as the user get inside to the site. every few hours, i mean, once in few hours to check via Ajax if there is new items for this time. the ajax working properly.

I get an error that say "Object reference not set to an instance of an object." and i don't really know what about is the error, is the model? is the partial name? what's wrong? or how to make it work.

Here is my code

foreach (dynamic item in rangeTime.Children)
                    {
                        var docType = item.ContentType.Alias;
                        var partialViewToShow = docType.ToString().Trim().ToLower().Replace(" ", "") == "birthday" ? "BDay" : "ContentPage";

                        st.Append(string.Format("<div class=\"custom-item\" data-time-to-show=\"{0}\">", item.slideTime));
                        st.Append(RenderPartialViewToString(partialViewToShow, item));
                        st.Append("</div>");
                    }

which call to this function: (fail on "viewResult.View.Render(viewContext, sw);")

 protected string RenderPartialViewToString(string viewName, object model)
    {
        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); // FAIL HERE

            return sw.GetStringBuilder().ToString();
        }
    }

In this case, the HttpCompileException means that the system was unable to render the PartialView because it could not compile the razor correctly.

I suggest adding the PartialView to the page using

foreach (dynamic item in rangeTime.Children)
{
    var docType = item.ContentType.Alias;
    var partialViewToShow = docType.ToString().Trim().ToLower().Replace(" ", "") == "birthday" ? "BDay" : "ContentPage";

    Html.Partial(partialViewToShow, item)
}

to see if you can get it to render before trying to render it as a string. Otherwise, maybe the inner exception will have more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM