今天,我与一个问题进行交互,我需要自己的html帮助程序来跟踪我需要的数据。
我想知道,如何创建自定义的html助手。
如何创建自定义的@Html。使用自定义代码?
答案 0 :(得分:2)
图像的基本但有用的html助手示例:
自定义助手:
using System;
using System.Web.Mvc;
namespace HelperApplication.Helpers
{
public static class CustomHelpers
{
public static string Image(string src, string alt = "Image", int width = 50, int height = 50)
{
return String.Format("<img src='{0}' alt=’{1}’ width=’{2}’ height=’{3}’/>", src, alt, width, height);
}
}
}
查看:
<div>
<span>Image with default values for alt, width, height</span>
@Html.Raw(@CustomHelpers.Image("imagePath"))
</div>
<div>
<span>Image with width=100 and height=100</span>
@Html.Raw(@CustomHelpers.Image("imagePath","Image With alt",100,100))
</div>
因为自定义html帮助器返回简单字符串然后我们可以将其编码为html字符串
使用@ Html.Raw()帮助程序并在其中包含必需的名称空间HelperApplication.Helpers
您希望使用自定义html帮助程序的视图..
答案 1 :(得分:1)
正如Exception的答案所示,编写HTML帮助程序的方法不止一种。然而,MVC中使用的约定是将它们作为扩展方法写在HtmlHelper
或HtmlHelper<TModel>
上。
您需要记住的最重要的事情是正确地转义HTML内容。默认情况下,Razor视图引擎将转义所有纯文本(字符串)。因此,您需要通过调用视图中的Html.Raw()
来包装内容,或使用IHtmlString
的实现。
但还有更多。当您将文本放入属性时,还需要考虑HTML具有某些要求。 HtmlHelper提供了正确转义的方法。
扩展Expection的代码示例,如下所示:
using System;
using System.Web.Mvc;
namespace HelperApplication.Helpers
{
public static class CustomHelpers
{
public static IHtmlString Image(this HtmlHelper html, string src, string alt = "", int width = 50, int height = 50)
{
return new MvcHtmlString(
string.Format("<img src='{0}' alt='{1}' width='{2}' height='{3}'/>",
html.AttributeEncode(src),
html.AttributeEncode(alt),
width,
height) );
}
}
}
您可以在视图中使用它:
<div>
<span>Image with default values for alt, width, height</span>
@Html.Image("/img/logo.jpg")
</div>
<div>
<span>Image with width=100 and height=100</span>
@Html.Image("/img/warning.png","Don't try this at home",100,100)
</div>
如果您想要更多灵活性,还有一个TagBuilder
可以帮助您生成正确的标记:
public static IHtmlString Image( this HtmlHelper html, string path, object htmlAttributes )
{
TagBuilder tagBuilder = new TagBuilder( "img" );
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes( htmlAttributes );
tagBuilder.MergeAttributes( attributes );
tagBuilder.Attributes["src"] = path;
return new MvcHtmlString( tagBuilder.ToString() );
}
虽然它确实有点复杂,但这将为您提供极大的灵活性。它允许您指定任何属性,甚至是客户端框架的自定义属性以及需要应用于元素的任何CSS。 要获得与上一个示例相同的结果,您可以像这样调用此帮助程序:
<div>
<span>Image with alt attribute and CSS for height and width</span>
@Html.Image("/img/warning.png", new { alt = "Don't try this at home", style="width:100px; height:100px" })
</div>