我有一个标签作为 <%= Html.Label(“”);%> 我想添加内容标签在运行时,不幸的是它doesn没有其他参数来为它创建id属性。我不能为它只是类似于ASP创建id属性:标签如何将内容添加到html.label在javascript asp.net mvc
感谢,
michaeld
我有一个标签作为 <%= Html.Label(“”);%> 我想添加内容标签在运行时,不幸的是它doesn没有其他参数来为它创建id属性。我不能为它只是类似于ASP创建id属性:标签如何将内容添加到html.label在javascript asp.net mvc
感谢,
michaeld
无需使用的HtmlHelper功能时时处处,如果他们不适合你的需求。他们只是想让你的生活更轻松,而不是更难。在这里使用优秀的HTML:
<label id="id_for_label"></label>
如果你想继续使用HtmlHelper函数,你总是可以创建自己的扩展方法。
例如:
public static class LabelHelper
{
private static string HtmlAttributes(object htmlAttributes)
{
var builder = new StringBuilder();
foreach (PropertyDescriptor descriptor in
TypeDescriptor.GetProperties(htmlAttributes))
{
builder.AppendFormat(" {0}=\"{1}\" ", descriptor.Name,
descriptor.GetValue(htmlAttributes));
}
return builder.ToString();
}
public static MvcHtmlString MyLabel(this HtmlHelper htmlHelper,
string labelText, object htmlAttributes)
{
var attributes = HtmlAttributes(htmlAttributes);
return MvcHtmlString.Create(
String.Format("<label for=\"{0}\" {1}>{0}</label",
labelText, attributes.Trim()));
}
}
然后,可以以下面的方式将标签添加至的视图:
<%: Html.MyLabel("Hello, World!", new { @id = "myLabel" })%>
生成的HTML是:
<label for="Hello, World!" id="myLabel">Hello, World!</label>
对于MVC 3这样的辅助功能已经可用:
http://msdn.microsoft.com/en-us/library/gg538318(v=VS.99).aspx
它是不是需要可见的属性,不工作! – michael