public static string Img(this HtmlHelper html, string src, string name)
{
TagBuilder tagBuilder = new TagBuilder("img");
tagBuilder.Attributes.Add("src", src);
tagBuilder.Attributes.Add("name", name);//为标签添加name属性及值
tagBuilder.GenerateId(name);//为标签生成Id,name参数代码Id的值
//创建经过HTML加密的字符串
//TagRenderMode.SelfClosing枚举值代表当前标签是自动关闭的
return tagBuilder.ToString(TagRenderMode.SelfClosing);
}
public static string Img(this HtmlHelper html, string src, string name, object htmlAttributes)
{
TagBuilder tag = new TagBuilder("img");
Type type = htmlAttributes.GetType();
foreach (PropertyInfo item in type.GetProperties())
{
string itemName = item.Name;
string itemValue = item.GetValue(htmlAttributes, null).ToString();
tag.Attributes.Add(itemName, itemValue);
}
tag.Attributes.Add("src", src);
tag.Attributes.Add("name", name);
return tag.ToString(TagRenderMode.SelfClosing);
}
<div>
<%= Html.Img("Content/images/Home.jpg", "img1")%>
</div>