I converted my web application from preview 3 to beta1 and am now trying to put the new functions of the framework to use. One of them is ModelBinding.
For this particular situation I created a class that is (for now) just a container of a bunch of simple-type properties. If I create a form with a bunch of textboxes, I want the framework to fill a SearchBag instance with these fields.
Any help is appreciated.
What Is Model Binding? ASP.NET MVC model binding allows mapping HTTP request data with a model. It is the procedure of creating . NET objects using the data sent by the browser in an HTTP request. Model binding is a well-designed bridge between the HTTP request and the C# action methods.
Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.
- Where do I start? Is this behaviour out of the box or do I implement a SearchBagBinder? I had a quick look at the IModelBinder but can't quite wrap my head around it and the DefaultModelBinder source doesn't make me any the wiser.
It is out of the box. You can either use UpdateModel or ModelBinder to acheive what you are looking to do.
- What is this ModelBindingContext?
This contains all the necessary information for the request to be bound to your Model. Similar to ControllerContext and ActionFilterContext, it is basically the state of the ModelBinder and contains all the information necessary to do what you want, if you follow the ASP.NET MVC teams recommendations for what the ModelBinder is supposed to do.
- How do I access my form fields?
context.HttpContext.Request.Forms["myformfield"];
or
foreach (var field in context.HttpContext.Request.Forms.Keys) {
var value = context.HttpContext.Request.Forms[field];
}
- What if the values are not passed on by a form but rather by entering a URL directly?
If you need to check both the Form and the QueryString just loop through both collections.
foreach (var field in context.HttpContext.Request.Forms.Keys) {
var value = context.HttpContext.Request.Forms[field];
}
foreach (var field in context.HttpContext.Request.QueryStrings.Keys) {
var value = context.HttpContext.Request.QueryStrings[field];
}
or you can loop through Param which will contain, Form, QueryString, Headers, etc.
foreach (var field in context.HttpContext.Request.Params.Keys) {
var value = context.HttpContext.Request.Params[field];
}
- Where do I find up-to-date information on this*(most blogs are outdated)? I thought I read a post by Phill at one time, but I can't seem to find it no more.
You have it right Phil is the best place for information as the PM of ASP.NET MVC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With