【发布时间】:2013-08-13 16:26:03
【问题描述】:
我正在 MVC 4 中构建一个 Html 助手,我想知道如何在 html 助手中正确构建标签/html。
例如,这里是一个简单的 html 帮助程序,它使用 TagBuilder 类创建图像标签:
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" />
哪个是更好的解决方案?
【问题讨论】:
标签: c# asp.net-mvc razor html-helper