How does the Html Helper, RenderPartial, work? How can I implement a helper that can bring in content from a partial view?

StackOverflow https://stackoverflow.com/questions/1283079

Question

When you use Html.RenderPartial is takes the name of the view you want to render, and renders it's content in that place.

I would like to implement something similar. I would like it to take the name of the view you want to render, along with some other variables, and render the content within a container..

For example:

public static class WindowHelper
{
    public static string Window(this HtmlHelper helper, string name, string viewName)
    {
        var sb = new StringBuilder();

        sb.Append("<div id='" + name + "_Window' class='window'>");
        //Add the contents of the partial view to the string builder.
        sb.Append("</div>");

        return sb.ToString();
    }
}

Anyone know how to do this?

Was it helpful?

Solution

The RenderPartial extensions are programmed to render directly to the Response object... you can see this in the source code for them:

....).Render(viewContext, this.ViewContext.HttpContext.Response.Output);

This means that if you change your approach a little bit, you can probably accomplish what you want. Rather than appending everything to a StringBuilder, you could do something like this:

using System.Web.Mvc.Html;

public static class WindowHelper
{
    public static void Window(this HtmlHelper helper, string name, string viewName)
    {
        var response = helper.ViewContext.HttpContext.Response;
        response.Write("<div id='" + name + "_Window' class='window'>");

        //Add the contents of the partial view to the string builder.
        helper.RenderPartial(viewName);

        response.Write("</div>");
    }
}

Note that including System.Web.Mvc.Html allows you access to the RenderPartial() methods.

OTHER TIPS

We are fixing this in MVC 2. You will be able to call Html.Partial() and get the actual contents of the view as a string.

Why not create a second view and have the partial inside that, pass Name as ViewData or in model etc..

Something like:

<div id='<%= ViewData["Name"] + "_Window"%>' class='window'>
   <% Html.RenderPartial(ViewData["Name"]); %>
</div>

Hope that helps, Dan

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top