3. Call model Bindings manually
1 @{2 viewbag.title = "Index"; 3} 4 5 @if (Tempdata.containskey ("MSG")) 6 {7
Then open HomeController and write the following code ( about ActionName can click this for reference ):
1 namespace mvcstudy.controllers 2 {3 Public class Homecontroller:controller 4 {5 private class TestA 6
{7 public String ID {get, set;} 8 } 9 public ActionResult Index () one { return View (); [Httppost]16 [ActionName ("Index")]17 public actionresult indexpost () { TestA ta = new TestA (); Updatemodel (TA), tempdata["msg"] = ta.id;22 return View (); }24 }25}
Here we manually bind through the Updatemodel , the final result and the same way as the formal parameters, the reader can test can find the input values are displayed, but the reader will be surprised, because the ID in TestA Not only in forms, but also in routedata and query strings , we can test this page with id=123 to see that the final result is not modified. One of the advantages of manually invoking model bindings is that we can control the source of the data, such as we modify the HomeController code as follows:
1 [Httppost]2 [ActionName ("Index")]3 public ActionResult indexpost () 4 {5 TestA ta = new TestA (); 6 Updatemodel (ta,new formvalueprovider (ControllerContext)); 7 tempdata["msg"] = ta.id;8 return View (); 9 }
Here we can see that we passed the second argument to Updatemodel ,formvalueprovider This means that the data source can only come from the form, and we can also modify it into a Routedatavalueprovider or querystringvalueprovider, the specific effect of the reader after you replace, enter http://localhost:1201/Home /index/123?id=asdsad test, you can look at the final display of the content is not from our designated source. In the way of using formal parameters we sometimes encounter the value we need in the HTTP stream, and the type of the parameter cannot be null, or we do not want it to be null, this time there will be an exception or an assignment of null, And through the Updatemodel can pass try...catch ... In the form of capturing InvalidOperationException exceptions so that they can be handled manually, if the reader does not wish to do so in this manner as in the following form:
1 if (TryUpdateModel (TA, New Querystringvalueprovider (ControllerContext))) 2 {3 //correct operation 4 }5 Else6 {7 //Exception action 8 }
So we can only judge by if .
4. Custom Value ProvidersBy the above we have found that the model binder that ASP. NET MVC has provided a lot of the functionality we need, but sometimes we think that some values are not from the HTTP Stream but we populate it ourselves, then this knowledge will interest you, Because below we are going to customize a value provider to complete our requirements. First introduce the interfaces and classes that need to be used, first of all the Ivalueprovider interfaces:
View CodeWhere Containsprefix is used to determine whether the prefix is something we can handle ( because ASP. NET MVC actually comes with a lot of this value provider, and finally calls these providers in a circular call until there is a return value.) then the GetValue method is to return the corresponding value, of course, the light has not enough, but also need a factory to create it to provide the call, this class is valueproviderfactory, And we just need to implement the Getvalueprovider method, is actually a new value provider and return, of course you can also through this method of ControllerContext Thus selectively returning a value provider, let's simply cite an example to handle ns.
Let's start by creating a Provider folder, and then create a new Nsvalueprovider class and write the following code in the file:
1 namespace Mvcstudy.provider 2 {3 Public class Nsvalueprovider:ivalueprovider 4 {5 6 public bool Cont Ainsprefix (string prefix) 7 {8 return String.Compare ("ns", prefix, true) = = 0; 9}10 one public Valueprov Iderresult GetValue (String key) {( containsprefix (key)) +- return new Valueproviderresult ("from NS", NULL, CultureInfo.InvariantCulture), }17 return null;18 }19 } Public class Nsvalueproviderfactory:valueproviderfactory22 {All public override Ivalueprovider Getvalueprovider (ControllerContext controllercontext) ( }27) ( nsvalueprovider); }28}
Finally open Global.asax to register it:
1 ValueProviderFactories.Factories.Insert (0, New nsvalueproviderfactory ());
Finally we need to modify the HomeController so that we can see the result:
1 public ActionResult Index (string ns) 2 {3 tempdata["msg"] = ns;4 return View (); 5 }
After recompiling, refresh the page and we can see the following results:
So we have finished a value provider, see this reader will be thinking how to customize the model provider, in fact, the model binder is to rely on the value of the provider to complete, you can understand it.
5. Model BinderThe model binder is similar to a value provider, except that you need to do a lot of work, because you are responsible for populating the properties of a class, so it's a bit cumbersome. Here is the interface Imodelbinderthat needs to be implemented:
1 namespace SYSTEM.WEB.MVC 2 {3 //Abstract: 4 // Define the methods required by the model binder. 5 Public Interface Imodelbinder 6 {7 //Summary: 8 // bind the model to a value using the specified controller context and binding context. 9 //10 //parameter: one // controllercontext:12 // controller context. //14 // bindingcontext:15 // binding context. //17 //Return Result: // binding value. Bindmodel Object (ControllerContext controllercontext, Modelbindingcontext bindingcontext); }21}
The focus here is the bindingcontext parameter, which contains many of the values and methods required for binding, and here is a simple example of customizing a model binder that is responsible for binding the following classes:
1 public class TestA2 {3 public String ID {get; set;} 4 }
It is also stipulated that the value can only be obtained by name for ns.id , and is not obtained according to the name of the parameter, the following is the code we implement the interface:
1 namespace Mvcstudy.provider 2 {3 Public class Nsmodelbinder:imodelbinder 4 {5 6 public Object BINDMO Del (ControllerContext ControllerContext, Modelbindingcontext BindingContext) 7 {8 TestA a = (TestA) Bindingcontext.model?? New TestA (); 9 bool Ishave = BindingContext.ValueProvider.ContainsPrefix ("Ns.id"), if (Ishave) one by one { a.id = BindingContext.ValueProvider.GetValue ("Ns.id"). attemptedvalue;13 }14 else15 { a.id = "ASD"; }18 return a;19 }20}21}
The final step, of course, is to register (Global.asax):
1 ModelBinders.Binders.Add (typeof (MvcStudy.Controllers.HomeController.TestA), New Nsmodelbinder ());
Then we recompile and enter values and commit in the page, and we can see that the ID of TestA is not the value we entered but the value in the model binder, but if we will views/home/index.cshtml After the name of the text box is changed to ns.id , we enter the value again, and finally we show the value we entered, thus we can see that the model binder is dependent on the value provider.
Now that the part about model binding is over, we'll start learning model validation.
Transferred from: http://www.cnblogs.com/yaozhenfa/p/asp_net_mvc_model_bind_2.html
ASP. NET MVC Learning Model bindings (2)