23

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 3

68

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly, I'd like to highlight this line: using System.Web.Mvc.Html.
0

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());
}

Comments

-2

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.

1 Comment

In some circumstances yes (probably including this one), but I try to keep my HTML in HTML like files where possible and use Html helpers to do the logic around how to combine them. This way I still get nice editor features in my html. However not using render partial is exactly what I've done in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.