5

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?

4

2 回答 2

3

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

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

于 2013-08-13T16:32:36.490 回答
0

第一种方法对内存中的字符串进行操作并正在执行,后者在资源方面更昂贵并且进行文件访问。

于 2013-08-13T16:30:47.870 回答