使用Razor或Tag构建器在Html Helper中构建Html?

Zil*_*ael 5 c# asp.net-mvc html-helper razor

我正在MVC 4中构建一个Html Helper,我想知道如何正确地在html助手中构建tags/html.

例如,这里是使用TagBuilder类创建图像标记的简单html帮助器:

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));
}
Run Code Online (Sandbox Code Playgroud)

从另一方面,我可以做这样的事情:

// 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" />
Run Code Online (Sandbox Code Playgroud)

哪个更好的解决方案?

Rus*_*Cam 3

两者都是有效的,但我怀疑后者要慢得多,并且我正在尝试看看它比使用部分视图有什么好处。

我的经验法则是 HtmlHelpers 应该只用于简单标记;任何更复杂的事情都应该使用部分视图和子操作。