Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Using Render Partial from Within an Html Helper

Tags:

I have an HtmlHelper extension that currently returns a string using a string builder and a fair amount of complex logic. I now want to add something extra to it that is taken from a render partial call, something like this ...

public static string MyHelper(this HtmlHelper helper) {     StringBuilder builder = new StringBuilder();     builder.Append("Hi There");     builder.Append(RenderPartial("MyPartialView"));     builder.Append("Bye!");     return builder.ToString(); } 

Now of course RenderPartial renders directly to the response so this doesn;t work and I've tried several solutions for rendering partials to strings but the all seem to fall over one I use the HtmlHelper within that partial.

Is this possible?

like image 506
Chris Meek Avatar asked Jan 18 '10 13:01

Chris Meek


People also ask

Which tag helper can you use to render a partial view?

The HTML Helper options for rendering a partial view include: @await Html. PartialAsync. @await Html.

How do you render a partial view inside a view in MVC?

Partial function which renders the Partial View. The name of the View and the object of the CustomerModel class are passed to the @Html. Partial function. In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.

Which is the way to render partial view using ASP.NET MVC?

Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .


1 Answers

Because this question, although old and marked answered, showed up in google, I'm going to give a different answer.

In asp.net mvc 2 and 3, there's an Html.Partial(...) method that works like RenderPartial but returns the partial view as a string instead of rendering it directly.

Your example thus becomes:

//using System.Web.Mvc.Html; public static string MyHelper(this HtmlHelper helper) {     StringBuilder builder = new StringBuilder();     builder.Append("Hi There");     builder.Append(helper.Partial("MyPartialView"));     builder.Append("Bye!");     return builder.ToString(); } 
like image 195
frank hadder Avatar answered Oct 29 '22 22:10

frank hadder