我创建了一个文本框助手来添加取自模型中字段的描述属性的标题(工具提示):
public static MvcHtmlString TextBoxForWithTitle<Tmodel, TProperty>(this HtmlHelper<Tmodel> htmlHelper, Expression<Func<Tmodel, TProperty>> expression, object htmlAttributes = null)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string textboxText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();
if (string.IsNullOrEmpty(textboxText))
return MvcHtmlString.Empty;
var textbox = new TagBuilder("input");
textbox.MergeAttributes(new RouteValueDictionary(htmlAttributes));
if (!string.IsNullOrEmpty(metaData.Description))
textbox.Attributes.Add("title", metaData.Description);
return MvcHtmlString.Create(textbox.ToString());
}
我知道复选框也是一个“输入”类型元素,但我不知道如何构造一个帮助器以使用描述作为标题。
public static MvcHtmlString CheckBoxForWithTitle<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string chkboxText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();
MemberExpression memberExpression = expression.Body as MemberExpression;
string parameterName = memberExpression.Member.Name;
if (string.IsNullOrEmpty(chkboxText))
return MvcHtmlString.Empty;
var chkbox = new MvcHtmlString(
string.Format(
"<input type=\"checkbox\" name=\"{0}\" id=\"{0}\" value=\"{1}\" {2} />",
parameterName,
chkbox.MergeAttributes(new RouteValueDictionary(htmlAttributes));
if (!string.IsNullOrEmpty(metaData.Description))
chkbox.Attributes.Add("title", metaData.Description);
return MvcHtmlString.Create(chkbox.ToString());
}
最佳答案
您当前的实现没有考虑模型绑定(bind)和 ModelState
,没有生成不引人注目的验证所需的属性,并且可能生成不正确的 id
属性。
在您自己的帮助程序中使用现有的 html 帮助程序方法,以便生成正确的 html。您的 TextBoxForWithTitle()
方法只需是
public static MvcHtmlString TextBoxForWithTitle<Tmodel, TProperty>(this HtmlHelper<Tmodel> htmlHelper, Expression<Func<Tmodel, TProperty>> expression, object htmlAttributes = null)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
IDictionary<string, object> attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (!string.IsNullOrEmpty(metaData.Description))
{
attributes.Add("title", metaData.Description);
}
return htmlHelper.TextBoxFor(expression, attributes);
}
类似地,CheckBoxForWithTitle()
是相同的,除了
return htmlHelper.CheckBoxFor(expression, attributes);
旁注:要了解现有帮助程序的实际工作原理,您可以查看源代码 here
关于asp.net-mvc - 使用模型描述中的标题属性创建 CheckboxFor MVC 帮助程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30127866/