Nie*_*ter 19 c# asp.net-mvc http-get custom-model-binder
我已经创建了一个自定义的MVC Model Binder,每次HttpPost
进入服务器都会调用它.但不会被HttpGet
要求提出要求.
GET
?如果是这样,我错过了什么?QueryString
从GET
请求?这是我的实施......
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.
}
}
Run Code Online (Sandbox Code Playgroud)
Global.asax中
protected void Application_Start()
{
ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
//...
}
Run Code Online (Sandbox Code Playgroud)
我已经研究过这些解决方案,但它们并不能满足我的需求:
TempData
?Name=John&Surname=Doe
)感谢@Felipe的帮助.为了防止有人与之斗争,我学到了:
GET
请求DefaultModelBinder
类GET
请求,这在你想到它时才有意义)Fel*_*ani 20
让我们说你有自己想要绑定的类型.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
// other properties you need
}
Run Code Online (Sandbox Code Playgroud)
您可以为此特定类型创建自定义模型绑定,继承自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 };
}
}
Run Code Online (Sandbox Code Playgroud)
在Application_Start
事件中的Global.asax中,您可以注册此模型绑定,以获取示例:
// for Person type, bind with the PersonModelBinder
ModelBinders.Binders.Add(typeof(Person), new PersonModelBinder());
Run Code Online (Sandbox Code Playgroud)
在BindModel
来自的方法中PersonModelBinder
,确保查询字符串中包含所有参数,并为它们提供理想的处理方法.
由于您有此操作方法:
public ActionResult Test(Person person)
{
// process...
}
Run Code Online (Sandbox Code Playgroud)
您可以使用以下网址访问此操作:
Test?id=7&name=Niels&age=25
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13747 次 |
最近记录: |