模型绑定器到底是做什么的?如何有效地使用它? [英] What, exactly, does a modelbinder do? How to use it effectively?

查看:63
本文介绍了模型绑定器到底是做什么的?如何有效地使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一些东西并遇到了 buildstarted.com 上的这篇博文 关于模型绑定器.它实际上对我的目的非常有效,但我不确定幕后到底发生了什么.我所做的是创建一个名为 USerModelBinder 的自定义 ModelBinder:

I was researching something and came across this blog post at buildstarted.com about model binders. It actually works pretty darn well for my purposes but I am not sure exactly whats going on behind the scenes. What I did was create a custom ModelBinder called USerModelBinder:

public class UserModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult value = bindingContext.ValueProvider.GetValue("id");
        MyEntities db = new MyEntities();
        User user = db.Users.SingleOrDefault(u => u.UserName == value.AttemptedValue);
        return user;
    }
}

然后在我的 Global.asax.cs 中:

ModelBinders.Binders.Add(typeof(User), new UserModelBinder());

我的理解是,使用模型绑定器使我不必在涉及用户"的每个控制器操作中使用以下行.因此,模型绑定器不会将id"传递给操作,而是拦截 id,获取正确的项目"(在我的情况下为用户)并将其转发给操作进行处理.

My understanding is that using the model binder allows me to NOT have to use the following lines in every controller action that involves a "User". So instead of passing in an "id" to the action, the modelbinder intercepts the id, fetches the correct "item"(User in my case) and forwards it to the action for processing.

        MyEntities db = new MyEntities();
        User user = db.Users.SingleOrDefault(u => u.UserName == value.AttemptedValue);

我还尝试在我的 User 类上使用注释,而不是使用 Global.asax.cs 中的行:

I also tried using an annotation on my User class instead of using the line in Global.asax.cs:

[ModelBinder(typeof(UserModelBinder))]
public partial class User
{
}

我不是在寻找 30 页的白皮书,但我不知道模型活页夹是如何做的.我只是想了解从提出请求到提供服务时会发生什么.我不能接受所有这些正常工作"的东西,哈哈.另外,使用注释与在 Global.asax.cs 中添加注释有什么区别吗?它们在我的测试中似乎工作相同,但有什么问题吗?

I'm not looking for a 30 page white paper but I have no idea how the model binder does what it does. I just want to understand what happens from when a request is made to the time it is served. All this stuff "just working" is not acceptable to me, lol. Also, is there any difference between using the annotation versus adding it in Global.asax.cs? They seem to work the same in my testing but are there any gotchas?

推荐答案

通常模型绑定器(在 MVC 中)查看您的 Action 方法并查看它需要什么(如对象类型).然后它会尝试从 HTTP 请求中找到值(HTTP 表单、QueryString、Json 中的值,可能还有其他地方,如使用 ValueProviders 的 cookie 等).然后它使用它检索到的参数创建一个新对象.

Usually the Model Binder (in MVC) looks at you Action method and sees what it requires (as in, the objects types). It then tries to find the values from the HTTP Request (values in the HTTP Form, QueryString, Json and maybe other places such as cookies etc. using ValueProviders). It then creates a new object with the parameters that it retrieves.

IMO 你所做的并不是真正的模型绑定".从某种意义上说,您刚刚读取了 id 并从数据库中获取了对象.

IMO What you've done is not really "model binding". In the sense that you've just read the id and fetched the object from the DB.

常用模型绑定示例:

// class
public class SomeClass
{
    public int PropA {get;set;}
    public string PropB {get;set;}
}

// action

public ActionResult AddSomeClass(SomeClass classToBind)
{
  // implementation
}

// pseudo html

      <form action="">
       <input name="PropA" type="text" />
       <input name="PropB" type="text" />
      </form>

如果您发布了一个包含正确值的表单(假设您发布了一个带有 PropA 和 PropB 的表单),模型绑定器可以识别您已经在表单中发送了这些值并构建了一个 SomeClass 对象.

if you post a form that contains the correct values (lets say you post a form with PropA and PropB ) the model binder can identify that you've sent those values in the form and build a SomeClass object.

如果你真的想创建一个真正的工作示例,你应该使用强类型视图并使用 HtmlHelper 的 EditorFor(或 EditorForModel)来创建 MVC 需要的所有正确名称.

If you really want to create a real working example you should use a strongly typed View and use HtmlHelper's EditorFor (or EditorForModel) to create all the correct names that MVC needs.

--

参考 MVC 的默认绑定器是 DefaultModelBinder,还有一些(还有更多,您可以在 System.Web.Mvc 命名空间中查看)它默认使用的 ValueProviders 是 FormValueProviderQueryStringValueProvider

for reference MVC's default binder is the DefaultModelBinder, and some (there are more, you can look around in the System.Web.Mvc namespace) ValueProviders that it uses by default are the FormValueProvider and the QueryStringValueProvider

所以,正如我已经说过的,这基本上是如何工作的,默认模型绑定器读取操作正在接收的模型(例如示例中的 SomeClass)读取它可以读取的值(例如 PropA 和 PropB)并要求 ValueProviders 提供正确的属性值.

So, as I already said, how this basically works is that the default model binder reads the model that the action is recieving (say SomeClass in the example) reads what are the values that it can read (say PropA and PropB) and asks the ValueProviders for the correct values for the properties.

此外,如果我没记错的话,您还可以使用 ValueProviderFactories 静态类在运行时查看值提供程序.

Also, if I recall correctly, you can also see the value providers in runtime using the ValueProviderFactories static class.

这篇关于模型绑定器到底是做什么的?如何有效地使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆