Custom Model Binder for ASP.NET MVC on GET request

后端 未结 1 1475
清酒与你
清酒与你 2020-12-31 02:22

I\'ve created a custom MVC Model Binder which gets called for every HttpPost that comes into the server. But does not get called for HttpGet reques

相关标签:
1条回答
  • 2020-12-31 02:34

    Let's supose you have your own type you want to bind.

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        // other properties you need
    }
    

    You can create a custom model bind for this specific type, inherithing from DefaultModelBinder, for sample:

    public class PersonModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var request = controllerContext.HttpContext.Request;
    
            int id = Convert.ToInt32(request.QueryString["id"]);
            string name = request.QueryString["name"];
            int age = Convert.ToInt32(request.QueryString["age"]);
            // other properties
    
            return new Person { Id = id, Name = name, Age = age };
        }
    }
    

    In the Global.asax in the Application_Start event, you can registry this model bind, for sample:

    // for Person type, bind with the PersonModelBinder
    ModelBinders.Binders.Add(typeof(Person), new PersonModelBinder());
    

    In the BindModel method from the PersonModelBinder, make sure you have all parameters in the querystring and give them the ideal treatment.

    Since you have this action method:

    public ActionResult Test(Person person)
    {
      // process...
    }
    

    You can access this action with an url something like this:

    Test?id=7&name=Niels&age=25
    
    0 讨论(0)
提交回复
热议问题