我有一个简单的字段表单
<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>
我怎样才能做到这一点?
All examples use EditorTemplates
但这是一个LabelFor
.
您可以通过创建自己的 HTML 帮助器来完成此操作。
http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs
您可以通过下载 ASP.Net MVC 的源代码来查看 LabelFor 的代码,并将其修改为自定义帮助程序。
Answer添加者巴莱桑德雷
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));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)