What, exactly, does a modelbinder do? How to use it effectively?

大城市里の小女人 提交于 2019-12-04 10:02:23

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 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.

example of usual model binding:

// 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>

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.

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.

--

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

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.

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

smartcaveman

A ModelBinder looks at the arguments of the selected Controller action's method signature, then converts the values from the ValueProviders into those arguments.

This happens when the ControllerActionInvoker invokes the action associated with the ControllerContext, because the Controller's Execute() method told it to.

For more about the ASP.NET MVC execution process, see Understanding the MVC Application Execution Process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!