gpt4 book ai didi

c# - HtmlHelper 扩展更改传入的属性的值

转载 作者:行者123 更新时间:2023-11-30 18:34:39 27 4
gpt4 key购买 nike

我有一个 html 帮助程序,可以以友好的方式显示文本框的电话号码。用法:

Html.PhoneNumberFor(m => m.PhoneNumber)

我希望它接受像“1111111111”这样的数字并输出“(111)111-1111”。我尝试通过从 html 助手扩展方法中的表达式中获取属性来更新 html 助手的 View 数据,但这似乎不起作用。那么,有人知道如何更新表达式对象中属性的值吗?这是不起作用的代码:

public static MvcHtmlString PhoneNumberFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, string>> expression, object htmlAttributes)
{
var value = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model as string;

if (!string.IsNullOrEmpty(value) && value.Length == 10)
{
value = string.Format("({0}){1}-{2}", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));

var fieldName = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
helper.ViewData[fieldName] = value;

}

return helper.TextBoxFor(expression, htmlAttributes);
}

最佳答案

我会为此创建一个自定义 DisplayFormatAttribute,然后您只需将它应用到 PhoneNumber 属性上。

关于c# - HtmlHelper 扩展更改传入的属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15887928/

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