使用Razor或标签构建器在HTML帮助器中构建HTML? [英] Building Html in Html Helper using Razor or Tag builder?

查看:55
本文介绍了使用Razor或标签构建器在HTML帮助器中构建HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在MVC 4中构建Html帮助器,我想知道如何在html帮助器中正确构建标签/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));
}

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

// 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" />

哪个是更好的解决方案?

解决方案

这两种方法都是有效的,但是我怀疑后者会慢很多,我正在尝试查看使用部分视图会带来什么好处./p>

我的经验法则是HtmlHelpers仅应用于简单标记;更为复杂的事情应该使用局部视图和子操作.

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?

解决方案

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.

这篇关于使用Razor或标签构建器在HTML帮助器中构建HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆