ASP.NET MVC2 - Custom Model Binder Examples

后端 未结 2 793
你的背包
你的背包 2020-12-23 15:27

I am trying to find some examples of building a custom model binder for a unique binding scenario I need to handle, but all of the articles I found were for older versions o

相关标签:
2条回答
  • 2020-12-23 15:45

    Take a look at several examples of Custom MVC Model binders on my blog.

    0 讨论(0)
  • 2020-12-23 16:04

    I don't know why you think a lot has changed since MVC 1 regarding custom model binders. But If I understand what you are trying to do, it should be fairly easy.

    public class CustomModelBinder : DefaultModelBinder {
        public override object BindModel(ControllerContext controllerContext, 
            ModelBindingContext bindingContext) {
    
            NameValueCollection form = controllerContext.HttpContext.Request.Form;
            //get what you need from the form collection
    
            //creata your model
            SomeModel myModel = new SomeMode();
            myModel.Property = "value";
            //or add some model errors if you need to
            ModelStateDictionary mState = bindingContext.ModelState;
            mState.Add("Property", new ModelState { });
            mState.AddModelError("Property", "There's an error.");
    
            return myModel; //return your model
        }
    }
    

    And your action :

    public ActionResult Contact([ModelBinder(typeof(CustomModelBinder))]SomeModel m){
        //...
    }
    

    Was that the kind of information you are looking for?

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