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

Viewed 13059

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?

3 Answers

I found the accepted answer printed out the viewable HTML on the page in ASP.NET MVC5 with for example:

@Html.ShowSomething(Model.MySubModel, "some text")

So I found the way to render it properly was to return an MvcHtmlString:

public static MvcHtmlString ShowSomething(this HtmlHelper helper, 
      MySubModel subModel, string someText)
{
    StringBuilder sb = new StringBuilder(someText);

    sb.Append(helper.Partial("_SomeOtherPartialView", subModel);

    return new MvcHtmlString(sb.ToString());
}

You shouldn't be calling partials from a helper. Helpers "help" your views, and not much else. Check out the RenderAction method from MVCContrib (if you need it now) or MVC v2 (if you can wait a few more months). You'd be able to pass your model to a standard controller action and get back a partial result.

Related