“This property setter is obsolete, because its value is derived from ModelMetadata.Model now.”

前端 未结 1 1321
终归单人心
终归单人心 2020-12-16 18:00

http://www.asp.net/learn/mvc/tutorial-39-cs.aspx

We are using the above guide to implement some validation in our ASP.NET MVC app.

We receive the following e

相关标签:
1条回答
  • 2020-12-16 18:30

    You will get this error when you create a new ModelBindingContext and then attempt to set the ModelType property, in MVC 2 preview 2 or higher. For example, in a unit test for a custom model binder in older versions of MVC, I had code like the following:

        internal static T Bind<T>(string prefix, FormCollection collection, ModelStateDictionary modelState) where T:class
        {
            var mbc = new ModelBindingContext()
            {
                ModelName = prefix,
                ModelState = modelState,
                ModelType = typeof(T),
                ValueProvider = collection.ToValueProvider()
            };
            IModelBinder binder = new MyModelBinder();
            var cc = new ControllerContext();
            return binder.BindModel(cc, mbc) as T;
        }
    

    When I updated to MVC 2 preview 2, I got the same error as you described. The fix was to change this code to this:

        internal static T Bind<T>(string prefix, FormCollection collection, ModelStateDictionary modelState) where T:class
        {
            var mbc = new ModelBindingContext()
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T)),
                ModelName = prefix,
                ModelState = modelState,
                ValueProvider = collection.ToValueProvider()
            };
            IModelBinder binder = new MyModelBinder();
            var cc = new ControllerContext();
            return binder.BindModel(cc, mbc) as T;
        }
    

    Note that I have removed the assignment of ModelType, and replaced it with an assignment to ModelMetadata. Visual Studio should tell you which line of code is actually throwing this error.

    0 讨论(0)
提交回复
热议问题