Building Html in Html Helper using Razor or Tag builder?

对着背影说爱祢 提交于 2019-12-07 05:02:22

问题


I am building a Html Helper in MVC 4 and I want to know how to build tags / html in the html helpers properly.

For example here is simple html helper that creates image tag using TagBuilder class:

public static MvcHtmlString Image(this HtmlHelper html, string imagePath, 
    string title = null, string alt = null)
{
    var img = new TagBuilder("img");
    img.MergeAttribute("src", imagePath);
    if (title != null) img.MergeAttribute("title", title);
    if (alt != null) img.MergeAttribute("alt", alt);

    return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
}

From another side I can do something like this:

// C#:
public static MvcHtmlString Image(this HtmlHelper html, string imagePath, 
    string title = null, string alt = null)
{
    var model = new SomeModel() {
        Path = imagePath,
        Title = title,
        Alt = alt
    };

    return MvcHtmlString.Create(Razor.Parse("sometemplate.cshtml", model));
}

// cshtml:
<img src="@model.Path" title="@model.Title" alt="@model.Alt" />

Which is the better solution?


回答1:


Both are valid, I would suspect the latter to be much slower however and I'm trying to see what benefits it would have over using a Partial View.

My rule of thumb is that HtmlHelpers should only be used for simple markup; anything more complicated should be using Partial Views and Child Actions.




回答2:


The first method operates on strings in memory and is performing, the latter is more expensive in terms of resources and makes a file access.



来源:https://stackoverflow.com/questions/18214347/building-html-in-html-helper-using-razor-or-tag-builder

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