[英]Custom Model Binder for ASP.NET MVC on GET request
I've created a custom MVC Model Binder which gets called for every HttpPost
that comes into the server. 我已经创建了一个自定义的MVC Model Binder,可以为进入服务器的每个
HttpPost
调用它。 But does not get called for HttpGet
requests. 但是没有调用
HttpGet
请求。
GET
? GET
期间调用我的自定义模型绑定器吗? If so, what did I miss? QueryString
from a GET
Request? GET
请求处理QueryString
自定义代码? Here's my implementation... 这是我的实施......
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 Global.asax中
protected void Application_Start()
{
ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
//...
}
I've looked into these solutions, but they don't quite work for what I'm looking for: 我已经研究过这些解决方案,但它们并不能满足我的需求:
TempData
TempData
复杂类型 ?Name=John&Surname=Doe
) ?Name=John&Surname=Doe
) Thanks to @Felipe for the help. 感谢@Felipe的帮助。 Just in case someone struggles with the same, I learnt:
为了防止有人与之斗争,我学到了:
GET
requests GET
请求 DefaultModelBinder
class DefaultModelBinder
类 GET
Requests, which makes sense when you think about it) GET
请求,这在你想到它时是有意义的) 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: 您可以为此特定类型创建自定义模型绑定,从
DefaultModelBinder
继承,以获取示例:
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: 在
Application_Start
事件的Global.asax中,您可以注册此模型绑定,以获取示例:
// 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. 在
BindModel
从方法PersonModelBinder
,请确保您有所有参数的查询字符串,并给他们理想的治疗方法。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.