开发者

How to test ModelBinders in ASP.Net Mvc 3

I'm trying to write some tests for a custom modelbinder and my god is this turning out difficult to stub. None of the stuff I'm finding online relates directly to ASP.Net Mvc 3 or tends to have very incomplete examples.

Spe开发者_StackOverflowcifically, the biggest wall I'm hitting is with bindingContext.ModelType - setting it explcitly throws an (runtime) error that the setter is obsoleted and that it is inferred from the Model parameter but the Model parameter for me is and should be null!


Hanselman explains this in great detail here:

http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx

Update: The above sample is obsolete. Read the comments on this post!


Thomas & George, you have to set the value provider on the ModelBindingContext. Below is an example of code in my HomeController Index action that creates a type and uses the default model binder to hydrate the object. This is just a simplified version, in my production code I actually take a param into the controller action that is the type and then create the type dynamically on the fly, works great when you want to send more than one type to a single controller action. Notice that ValueProvider and ControllerContext are properties of the controller.

        HomeModel test = new HomeModel();
        ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => test, test.GetType());
        ModelBindingContext modelBindingContext = new ModelBindingContext { ModelMetadata = metadata, ValueProvider = ValueProvider};


        DefaultModelBinder defaultModelBinder = new DefaultModelBinder();
        defaultModelBinder.BindModel(ControllerContext, modelBindingContext);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜