gpt4 book ai didi

asp.net - 如何创建一个 HTML Helper 来扩展 TextBoxFor() 以添加 CSS 样式?

转载 作者:行者123 更新时间:2023-12-04 04:47:20 26 4
gpt4 key购买 nike

如何创建一个 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));
}

关于asp.net - 如何创建一个 HTML Helper 来扩展 TextBoxFor() 以添加 CSS 样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11232041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com