Adapting a Custom Html Helper for Razor (it uses HtmlTextWriter so returns void)

╄→гoц情女王★ 提交于 2019-12-01 22:07:49
marcind

Contrary to the responses you received for your other question Razor does not require that you return an HtmlString. The problem with your code right now is that you are writing directly to the response stream. Razor executes things inside-out which means that you can mess up the response order (see a similar question).

So in your case you could probably do this (though i haven't tested it):

public static void Theseus(this HtmlHelper html)
{
    var writer = new HtmlTextWriter(html.ViewContext.Writer);
    ...
}

Edit (follow up to address your comments):

Html Helpers are perfectly capable of either returning a HtmlString directly or void and writing to the context writer. For example, both Html.Partial and Html.RenderPartial work fine in Razor. I think what you are confusing is the syntax required to call one version and not the other.

For example, consider an Aspx view:

<%: Html.Partial("Name") %>
<% Html.RenderPartial("Name") %>

You call each method differently. If you flip things around, things will just not work. Similarly in Razor:

@Html.Partial("Name")
@{ Html.RenderPartial("Name"); }

Now it just so happens that the syntax to use a void helper is a lot more verbose in Razor compared to Aspx. However, both work just fine. Unless you meant something else by "the issue is with a html helper not being able to return void".

By the way, if you really want to call your helper using this syntax: @Html.Theseus() you could do this:

public static IHtmlString Theseus(this HtmlHelper html)
{
    var writer = new HtmlTextWriter(html.ViewContext.Writer);
    ...
    return new HtmlString("");
}

But that's a bit of a hack.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!