GET请求上ASP.NET MVC的自定义模型Binder
我已经创建了一个自定义的MVC Model Binder,可以为进入服务器的每个HttpPost
调用它。 但是没有调用HttpGet
请求。
- 我应该在
GET
期间调用自定义模型绑定器吗? 如果是这样,我错过了什么? - 如果没有,我如何编写处理来自
GET
请求的QueryString
自定义代码?
这是我的实施……
public class CustomModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { // This only gets called for POST requests. But I need this code for GET requests. } }
Global.asax中
protected void Application_Start() { ModelBinders.Binders.DefaultBinder = new CustomModelBinder(); //... }
我已经研究过这些解决方案,但它们并不能满足我的需求:
- 通过
TempData
复杂类型 - 使用默认绑定器构建复杂类型(
?Name=John&Surname=Doe
)
备注答案
感谢@Felipe的帮助。 为了防止有人与之斗争,我学到了:
- 自定义模型绑定器可用于
GET
请求 - 您可以使用
DefaultModelBinder
类 - 我的想法是动作方法必须有一个参数 (否则会跳过模型绑定器以
GET
请求,这在您考虑它时是有意义的)
让我们假设您有自己想要绑定的类型。
public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } // other properties you need }
您可以为此特定类型创建自定义模型绑定,从DefaultModelBinder
inheritance,以获取示例:
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 }; } }
在Application_Start
事件的Global.asax中,您可以注册此模型绑定,以获取示例:
// for Person type, bind with the PersonModelBinder ModelBinders.Binders.Add(typeof(Person), new PersonModelBinder());
在BindModel
方法中,确保在查询字符串中包含所有参数并为它们提供理想的处理。
由于您有此操作方法:
public ActionResult Test(Person person) { // process... }
您可以使用以下url访问此操作:
Test?id=7&name=Niels&age=25