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

发布于 2024-12-02 02:18:58 字数 331 浏览 2 评论 0原文

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

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

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

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

I know on the Razor View file, we can do something like this
@Html.TextBox("username", null, new { maxlength = 20, autocomplete = "off" })

However, I am hoping to create a model for the MVC that can be used to create a form with explicitly defined the size and max length of the textboxes. I try [StringLength(n)] on top of the properties of the model, but that seems to only do the validation ratherh set the size of the textbox.

Is there anyway that we can define the length of the text field as a data annotation on top of a property of a model?

So ultimately, we could just create the whole form by using razor to map to a model rather than explicitly pick up the model properties one by one in order to set the textbox size.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

弥繁 2024-12-09 02:18:58

以下是使用 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);
}

Here is a outline of a custom helper that uses 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);
}
思念绕指尖 2024-12-09 02:18:58

这不行吗?

public class ViewModel
{
    [StringLength(20)]
    public string UserName {get;set;}
}

在视图中:

@Html.TextBoxFor(x => x.UserName, new {autocomplete = "off"})

或:

@Html.EditorFor(x => x.UserName)

Does this not work?

public class ViewModel
{
    [StringLength(20)]
    public string UserName {get;set;}
}

In the View:

@Html.TextBoxFor(x => x.UserName, new {autocomplete = "off"})

or:

@Html.EditorFor(x => x.UserName)
镜花水月 2024-12-09 02:18:58

我发现我更喜欢只调用 Html.EditorFor(...) 的观点。这意味着编辑器和显示模板决定了我视图中控件的命运,这样我的视图代码就被清理了很多 - 它只有 html 和编辑器的通用请求。

以下链接提供了在编辑器模板中实现此功能的工作示例
https://jefferytay.wordpress.com/2011/12/20/asp-net-mvc-string-editor-template-which-handles-the-stringlength-attribute/

我'我在我的 String.cshtml 编辑器模板中使用类似的内容(位于 Shared/EditorTemplates 中)。

@model object
@using System.ComponentModel.DataAnnotations
@{
    ModelMetadata meta = ViewData.ModelMetadata;
    Type tModel = meta.ContainerType.GetProperty(meta.PropertyName).PropertyType;
}
@if(typeof(string).IsAssignableFrom(tModel)) {

    var htmlOptions = new System.Collections.Generic.Dictionary<string, object>();

    var stringLengthAttribute = (StringLengthAttributeAdapter)ViewData.ModelMetadata.GetValidators(this.ViewContext.Controller.ControllerContext).Where(v => v is StringLengthAttributeAdapter).FirstOrDefault();
    if (stringLengthAttribute != null && stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"] != null)
    {
        int maxLength = (int)stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"];

        htmlOptions.Add("maxlength", maxLength);

        if (maxLength < 20)
        {
            htmlOptions.Add("size", maxLength);
        }
    }

    htmlOptions.Add("class", "regular-field");

    <text>
         @Html.TextBoxFor(m => m, htmlOptions)
    </text>
}
else if(typeof(Enum).IsAssignableFrom(tModel)) {
    //Show a Drop down for an enum using:
    //Enum.GetValues(tModel)
    //This is beyond this article
}
//Do other things for other types...

然后我的 model 被注释,例如:

[Display(Name = "Some Field", Description = "Description of Some Field")]
[StringLength(maximumLength: 40, ErrorMessage = "{0} max length {1}.")]
public string someField{ get; set; }

我的 View 只是调用:

<div class="editor-label">
    @Html.LabelWithTooltipFor(model => model.something.someField)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.something.someField)
    @Html.ValidationMessageFor(model => model.something.someField)
</div>

您可能还注意到我的 String.cshtml 编辑器模板也自动神奇地处理 Enum,但这正在开始偏离当前主题,所以我取消了该代码,我只是在这里说字符串编辑器模板可以增加额外的重量,并且谷歌可能对此有一些https://www.google.com/search?q=string+editor+template +enum

Label With Tooltip For 是一个自定义 HTML 帮助器,只需将说明放入标签标题中,即可获取有关将鼠标悬停在每个标签上的更多信息。

如果您想在编辑器模板中执行此操作,我建议您使用此方法。

I find that I prefer my views to just Call Html.EditorFor(...). This means that the Editor and Display templates decide the fate of controls in my view, such that my view code gets cleaned up a lot - it just has html and generic requests for editors.

The following link gives a working sample of getting this working in an Editor Template
https://jefferytay.wordpress.com/2011/12/20/asp-net-mvc-string-editor-template-which-handles-the-stringlength-attribute/

I'm using similar in my String.cshtml Editor Template (goes in Shared/EditorTemplates ).

@model object
@using System.ComponentModel.DataAnnotations
@{
    ModelMetadata meta = ViewData.ModelMetadata;
    Type tModel = meta.ContainerType.GetProperty(meta.PropertyName).PropertyType;
}
@if(typeof(string).IsAssignableFrom(tModel)) {

    var htmlOptions = new System.Collections.Generic.Dictionary<string, object>();

    var stringLengthAttribute = (StringLengthAttributeAdapter)ViewData.ModelMetadata.GetValidators(this.ViewContext.Controller.ControllerContext).Where(v => v is StringLengthAttributeAdapter).FirstOrDefault();
    if (stringLengthAttribute != null && stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"] != null)
    {
        int maxLength = (int)stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"];

        htmlOptions.Add("maxlength", maxLength);

        if (maxLength < 20)
        {
            htmlOptions.Add("size", maxLength);
        }
    }

    htmlOptions.Add("class", "regular-field");

    <text>
         @Html.TextBoxFor(m => m, htmlOptions)
    </text>
}
else if(typeof(Enum).IsAssignableFrom(tModel)) {
    //Show a Drop down for an enum using:
    //Enum.GetValues(tModel)
    //This is beyond this article
}
//Do other things for other types...

Then my model is annotated such as:

[Display(Name = "Some Field", Description = "Description of Some Field")]
[StringLength(maximumLength: 40, ErrorMessage = "{0} max length {1}.")]
public string someField{ get; set; }

And my View simply calls:

<div class="editor-label">
    @Html.LabelWithTooltipFor(model => model.something.someField)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.something.someField)
    @Html.ValidationMessageFor(model => model.something.someField)
</div>

You might also notice that my String.cshtml Editor Template also auto-magically handles Enum's, but that is starting to digress from the current topic, so I nixed that code, I'll just say here that the String Editor Template can pull extra weight, and likely google has someting on that https://www.google.com/search?q=string+editor+template+enum

Label With Tooltip For is a custom HTML helper that just drops the description into the label title, for more information on mouse over for every label.

I'd recommend this approach if you want to do this in an Editor Template.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文