我有一个简单的字段表单
<div class="field fade-label">
@Html.LabelFor(model => model.Register.UserName)
@Html.TextBoxFor(model => model.Register.UserName)
</div>
结果是:
<div class="field fade-label">
<label for="Register_UserName">Username (used to identify all services, from 4 to 30 chars)</label>
<input type="text" value="" name="Register.UserName" id="Register_UserName">
</div>
但我想要那个LabelFor
代码附加 <span>
在里面,这样我最终可以得到:
<label for="Register_UserName">
<span>Username (used to identify all services, from 4 to 30 chars)</span>
</label>
我该怎么做?
全部examples使用EditorTemplates
但这是LabelFor
.
最佳答案
您可以通过创建自己的 HTML 帮助器来完成此操作。
http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs
您可以通过下载 ASP.Net MVC 源代码来查看 LabelFor<> 的代码,并将其修改为自定义帮助程序。
<小时/>答案由 balexandre 添加
public static class LabelExtensions
{
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(labelText))
{
return MvcHtmlString.Empty;
}
TagBuilder tag = new TagBuilder("label");
tag.MergeAttributes(htmlAttributes);
tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
TagBuilder span = new TagBuilder("span");
span.SetInnerText(labelText);
// assign <span> to <label> inner html
tag.InnerHtml = span.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}
}
关于asp.net-mvc - 如何覆盖 @Html.LabelFor 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5196290/