9

ここに私のViewModelのプロパティ:

[Display(Name = "Ext.")]
[MaxLength(6, ErrorMessage = "Must be a maximum of 6 characters")]
[StringLength(6)]
public string Extension { get; set; }

そして私の見解では:

@Html.EditorFor(model => model.Extension)

そしてそれはレンダリングします:

<input class="text-box single-line" data-val="true" data-val-length="The field Ext. must be a string with a maximum length of 6." data-val-length-max="6" id="Extension" name="Extension" type="text" value="" />

これはテキストボックスの maxlength 属性を設定する必要がありますか? そうでない場合、どうすれば DataAttributes でそれを行うことができますか?

4

3 に答える 3

4

基本的にブラッドの回答に基づいており、ラムダ構文を使用して Html ヘルパーの拡張機能にラップされているため、Razor ビューをリフレクションで汚染することはありません。

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc;

public static class HtmlHelper
{
    public static int? MaxLength<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression)
    {
        MemberExpression memberExpression = (MemberExpression)expression.Body;

        PropertyInfo property = typeof(TModel)
            .GetProperty(memberExpression.Member.Name);

        StringLengthAttribute attribute = (StringLengthAttribute)property
            .GetCustomAttributes(typeof(StringLengthAttribute), true)
            .FirstOrDefault();

        if (attribute != null)
        {
            return attribute.MaximumLength;
        }

        return null;
    }
}

次のように使用します。

@Html.TextBoxFor(x => x.Name, new { maxlength = Html.MaxLength(x => x.Name) })

どこでxあなたのモデルを指します。

StringLengthAttributeプロパティに対して が宣言されていない場合、nullが返さmaxlengthれ、テキスト ボックス要素の属性は空になります。

メソッドにアクセスできるように、かみそりのページに using を含めることを忘れないでください。

@using HtmlHelper

また、コンパイル エラーを克服するために、メソッドに null 許容結果を使用しない必要があります。

于 2016-10-13T19:54:13.540 に答える
2

私は似たようなことに遭遇しました。ここに私の迅速で汚い解決策があります:

.cshtml ファイルの先頭に次の行を追加します。

@{
var max = ((System.ComponentModel.DataAnnotations.StringLengthAttribute)(typeof(MyType))
.GetProperty("MyProp")
.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), true)[0]).MaximumLength;    
}

その下の html で、EditorFor を次のように置き換えます。

@Html.TextBoxFor(model => model.Extension, htmlAttributes: new {maxlength=max })

私は最終的に、スクリプトでそれを行うほうがよいと判断しました。

<script>
    $(function ()
    {
        var max = $("#myinput").attr("data-val-length-max");
        $("#myinput").attr("maxlength", max);
    });
</script>

ただし、スクリプトを追加したくない場合は、最初の例が機能するはずです。

于 2013-11-01T23:42:19.650 に答える