gpt4 book ai didi

asp.net-mvc-3 - ASP.NET MVC3 - 文本框渲染的数据注释和最大长度/大小

转载 作者:行者123 更新时间:2023-12-02 14:09:34 25 4
gpt4 key购买 nike

我知道在 Razor View 文件中,我们可以做这样的事情@Html.TextBox("用户名", null, new { maxlength = 20, autocomplete = "off"})

但是,我希望为 MVC 创建一个模型,可用于创建一个明确定义文本框大小和最大长度的表单。我在模型的属性之上尝试 [StringLength(n)],但这似乎只是进行验证而不是设置文本框的大小。

我们是否可以将文本字段的长度定义为模型属性之上的数据注释?

最终,我们可以通过使用 razor 映射到模型来创建整个表单,而不是显式地一一选取模型属性来设置文本框大小。

最佳答案

以下是使用 StringLengthAttribute 的自定义帮助器的概述。

public class MyModel
{
[StringLength(50)]
public string Name{get; set;}
}

public MvcHtmlString MyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression)
{

var attributes = new Dictionary<string, Object>();
var memberAccessExpression = (MemberExpression)expression.Body;
var stringLengthAttribs = memberAccessExpression.Member.GetCustomAttributes(
typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), true);

if (stringLengthAttribs.Length > 0)
{
var length = ((StringLengthAttribute)stringLengthAttribs[0]).MaximumLength;

if (length > 0)
{
attributes.Add("size", length);
attributes.Add("maxlength", length);
}
}

return helper.TextBoxFor(expression, attributes);
}

关于asp.net-mvc-3 - ASP.NET MVC3 - 文本框渲染的数据注释和最大长度/大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7231445/

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