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

When you use Html.RenderPartial it takes the name of the view you want to display and displays its contents in that place.

I would like to implement something like this. I would like it to take the name of the view you want to display, along with some other variables, and display the contents in the 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(); } } 

Does anyone know how to do this?

+6
c # asp.net-mvc html-helper partial-views renderpartial
source share
3 answers

RenderPartial extensions are programmed to directly display 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 bit, you can probably accomplish what you want. Instead of adding everything to StringBuilder, you can 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 to access the RenderPartial () methods.

+8
source share

We fix this in MVC 2. You can call Html.Partial () and get the actual contents of the view as a string.

+8
source share

Why not create a second view and have a partial view inside it, pass the name as ViewData or to the model, etc.

Something like:

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

Hope this helps, Dan

0
source share

All Articles