我創建了一個文本框助手添加標題(提示)從描述屬性在模型中採取現場title屬性:創建CheckboxFor MVC助手與模型描述
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());
}
謝謝Stephen!我知道我必須以某種方式回到實際的幫手項目! –