Tuesday, June 26, 2012

ASP.Net MVC: Controllers - Model Binding



The data sent by web client can be automatically bound to .NET objects. MVC Model Binding searches for data in the following order.

  1. Routing Data
  2. Query String
  3. Posted Form Values
public class AccountController : Controller
{
  public ActionResult Search(string q)
  {
      ..
  }
}
  1. Given URL Account/Search/1001, Model Binding will find q to be 1001
  2. Given URL Account/Search?q=1001, Model Binding will find q to be 1001
  3. Given URL Account/Search/1001?q=2002, Model Binding will find q to be 1001
  4. In the absence of a value for q, Model Binding will try to find a POSTed value for field named q

The HTML Input tag names are the same as the names of Model properties. That makes binding possible.
Model binder makes life easier. Automatically grabs information from the url, query string, or posted form values.

Edit Example

public ActionResult Edit (int id)
{
  var review = _db.Reviews.FindById (id);
  return View(review);
}

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var review = _db.Reviews.FindById(id);

if (TryUpdateModel (review))  
// model binder is invoked; values moved into the model
// and validation rules pass
{
  _db.SaveChanges();
  return RedirectToAction(“Index”);
 }

  return View(review);  // re-render the view with the preserved values (TryUpdateModel above)
}