如何创建一个HTML Helper来扩展TextBoxFor()以添加CSS样式?
@Html.TextBoxFor(model => model.FirstName,new { @class = "txt" })
解决方法
public static System.Web.Mvc.MvcHtmlString DtxTextBoxFor<TModel,TValue> (this System.Web.Mvc.HtmlHelper<TModel> html,System.Linq.Expressions.Expression<System.Func<TModel,TValue>> expression,System.Collections.Generic.IDictionary<string,object> htmlAttributes = null,bool readOnly = false) { if (htmlAttributes == null) { htmlAttributes = new System.Collections.Generic.Dictionary<string,object>(); } System.Web.Mvc.ModelMetadata oModelMetadata = System.Web.Mvc.ModelMetadata.FromLambdaExpression(expression,html.ViewData); if (oModelMetadata == null) { if (readOnly) { if (htmlAttributes.ContainsKey("readonly") == false) { htmlAttributes.Add("readonly","read-only"); } } } else { if (htmlAttributes.ContainsKey("placeholder") == false) { string strHtmlFieldName = System.Web.Mvc.ExpressionHelper.GetExpressionText(expression); string strLabelText = oModelMetadata.displayName ?? oModelMetadata.PropertyName ?? strHtmlFieldName.Split('.').Last(); if (string.IsNullOrEmpty(strLabelText) == false) { htmlAttributes.Add("placeholder",strLabelText); } } if ((readOnly) || (oModelMetadata.IsReadOnly)) { if (htmlAttributes.ContainsKey("readonly") == false) { htmlAttributes.Add("readonly","read-only"); } } } htmlAttributes.Add("class","form-control"); System.Linq.Expressions.MemberExpression oMemberExpression = expression.Body as System.Linq.Expressions.MemberExpression; if (oMemberExpression != null) { System.ComponentModel.DataAnnotations.StringLengthAttribute oStringLengthAttribute = oMemberExpression.Member.GetCustomAttributes (typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute),false) .FirstOrDefault() as System.ComponentModel.DataAnnotations.StringLengthAttribute; if (oStringLengthAttribute != null) { if (htmlAttributes.ContainsKey("maxlength") == false) { htmlAttributes.Add("maxlength",oStringLengthAttribute.MaximumLength); } } } return (html.TextBoxFor(expression,htmlAttributes)); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。