5

ASP.NET MVCでサーバー側の検証にデータ注釈を使用するために、 DataAnnotationsModelBinderを使用しようとしています。

私のViewModelが、次のような即時プロパティを持つ単純なクラスである限り、すべてが正常に機能します。

public class Foo
{
    public int Bar {get;set;}
}

ただし、次のような複雑なものを使用しようとするとDataAnnotationsModelBinderNullReferenceExceptionViewModel

public class Foo
{
    public class Baz
    {
        public int Bar {get;set;}
    }

    public Baz MyBazProperty {get;set;}
}

ViewModelこれは、複数のLINQエンティティをレンダリングするビューにとって大きな問題です。これは、型指定されていないViewData配列ではなく、複数のLINQエンティティを含むカスタムを使用することを本当に好むためです。

にはこのDefaultModelBinder問題がないため、のバグのようですDataAnnotationsModelBinder。これに対する回避策はありますか?

編集:考えられる回避策は、もちろん、次のようにViewModelクラスで子オブジェクトのプロパティを公開することです。

public class Foo
{
    private Baz myBazInstance;

    [Required]
    public string ExposedBar
    {
        get { return MyBaz.Bar; }
        set { MyBaz.Bar = value; }
    }

    public Baz MyBaz
    {
        get { return myBazInstance ?? (myBazInstance = new Baz()); }
        set { myBazInstance = value; }
    }

    #region Nested type: Baz

    public class Baz
    {
        [Required]
        public string Bar { get; set; }
    }

    #endregion
}

#endregion

しかし、私はこの余分なコードをすべて書く必要がないことを望んでいます。そのDefaultModelBinderようなhiearchiesでDataAnnotationsModelBinderうまくいくので、私もそうすべきだと思います。

2番目の編集:これは確かにのバグのようDataAnnotationsModelBinderです。ただし、次のASP.NETMVCフレームワークバージョンが出荷される前にこれが修正される可能性があります。詳細については、このフォーラムスレッドを参照してください。

4

2 に答える 2

8

私は今日、まったく同じ問題に直面しました。あなた自身のように、ビューをモデルに直接結び付けるのではなく、モデルのインスタンスと、ビューに送信したいパラメーター/構成を保持する中間のViewDataModelクラスを使用します。

BindPropertyを回避するためにDataAnnotationsModelBinderを変更することになりましたがNullReferenceException、個人的には、プロパティが有効な場合にのみバインドされるのが好きではありませんでした(以下の理由を参照)。

protected override void BindProperty(ControllerContext controllerContext,
                                         ModelBindingContext bindingContext,
                                         PropertyDescriptor propertyDescriptor) {
    string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);

    // Only bind properties that are part of the request
    if (bindingContext.ValueProvider.DoesAnyKeyHavePrefix(fullPropertyKey)) {
        var innerContext = new ModelBindingContext() {
            Model = propertyDescriptor.GetValue(bindingContext.Model),
            ModelName = fullPropertyKey,
            ModelState = bindingContext.ModelState,
            ModelType = propertyDescriptor.PropertyType,
            ValueProvider = bindingContext.ValueProvider
        };

        IModelBinder binder = Binders.GetBinder(propertyDescriptor.PropertyType);
        object newPropertyValue = ConvertValue(propertyDescriptor, binder.BindModel(controllerContext, innerContext));
        ModelState modelState = bindingContext.ModelState[fullPropertyKey];
        if (modelState == null)
        {
            var keys = bindingContext.ValueProvider.FindKeysWithPrefix(fullPropertyKey);
            if (keys != null && keys.Count() > 0)
                modelState = bindingContext.ModelState[keys.First().Key];
        }
        // Only validate and bind if the property itself has no errors
        //if (modelState.Errors.Count == 0) {
            SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
            if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue)) {

                OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
            }
        //}

        // There was an error getting the value from the binder, which was probably a format
        // exception (meaning, the data wasn't appropriate for the field)
        if (modelState.Errors.Count != 0) {
            foreach (var error in modelState.Errors.Where(err => err.ErrorMessage == "" && err.Exception != null).ToList()) {
                for (var exception = error.Exception; exception != null; exception = exception.InnerException) {
                    if (exception is FormatException) {
                        string displayName = GetDisplayName(propertyDescriptor);
                        string errorMessage = InvalidValueFormatter(propertyDescriptor, modelState.Value.AttemptedValue, displayName);
                        modelState.Errors.Remove(error);
                        modelState.Errors.Add(errorMessage);
                        break;
                    }
                }
            }
        }
    }
}

また、有効かどうかに関係なく、プロパティのデータを常にバインドするように変更しました。このようにして、無効なプロパティをnullにリセットせずに、モデルをビューに戻すことができます。

コントローラの抜粋

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(ProfileViewDataModel model)
{
    FormCollection form = new FormCollection(this.Request.Form);
    wsPerson service = new wsPerson();
    Person newPerson = service.Select(1, -1);
    if (ModelState.IsValid && TryUpdateModel<IPersonBindable>(newPerson, "Person", form.ToValueProvider()))
    {
        //call wsPerson.save(newPerson);
    }
    return View(model); //model.Person is always bound no null properties (unless they were null to begin with)
}

私のModelクラス(Person)はWebサービスから取得されているため、属性を直接配置することはできません。これを解決する方法は次のとおりです。

ネストされたDataAnnotationsの例

[Validation.MetadataType(typeof(PersonValidation))]
public partial class Person : IPersonBindable { } //force partial.

public class PersonValidation
{
    [Validation.Immutable]
    public int Id { get; set; }
    [Validation.Required]
    public string FirstName { get; set; }
    [Validation.StringLength(35)]
    [Validation.Required]
    public string LastName { get; set; }
    CategoryItemNullable NearestGeographicRegion { get; set; }
}

[Validation.MetadataType(typeof(CategoryItemNullableValidation))]
public partial class CategoryItemNullable { }

public class CategoryItemNullableValidation
{
    [Validation.Required]
    public string Text { get; set; }
    [Validation.Range(1,10)]
    public string Value { get; set; }
}

ここで、フォームフィールドをにバインドする[ViewDataModel.]Person.NearestGeographicRegion.Text[ViewDataModel.]Person.NearestGeographicRegion.Value、ModelStateがそれらを正しく検証し始め、DataAnnotationsModelBinderもそれらを正しくバインドします。

この答えは決定的なものではなく、今日の午後に頭をかいた結果です。ブライアンウィルソンが開始したプロジェクトの単体テストと私自身の限定的なテストのほとんどに合格しましたが、適切にテストされていません。この問題の真の終結については、この解決策についてのBradWilsonの考えを聞いてみたいと思います。

于 2009-05-14T17:04:18.610 に答える
3

Martijnが指摘しているように、この問題の修正は簡単です。

BindPropertyメソッドには、次のコード行があります。

if (modelState.Errors.Count == 0) {

次のように変更する必要があります。

if (modelState == null || modelState.Errors.Count == 0) {

DataAnnotationsModelBinderを含むMVC2にDataAnnotationsサポートを含める予定です。この機能は、最初のCTPの一部になります。

于 2009-06-14T02:11:53.083 に答える