tags:

views:

249

answers:

3

Hello, I'm wondering what the real measurable advantage to using Modelbinders is?

A: 

Model Binders

A model binder in MVC provides a simple way to map posted form values to a .NET Framework type and pass the type to an action method as a parameter. Binders also give you control over the deserialization of types that are passed to action methods. Model binders are like type converters, because they can convert HTTP requests into objects that are passed to an action method. However, they also have information about the current controller context.

From here.

Mitch Wheat
+1  A: 

Rather than getting primitives sent into your action:

public ActionResult Search(string tagName, int numberOfResults)

you get a custom object:

public ActionResult Search(TagSearch tagSearch)

This makes your Search action "thinner" (a good thing), much more testable and reduces maintenance.

Chris Missal
Did you get the two examples switched around?
DSO
A: 

Here's another benefit:

You can create modelbinders that retrieves an object from the database just given an ID.

This will allow you to get actions like this

// GET /Orders/Edit/2
public ActionResult Edit(Order order){
  return View(order);
}

And the custom ModelBinder would do the datafetching for you, keeping your controller skinny.

Without that ModelBinder it could look like this:

// GET /Orders/Edit/2
public ActionResult Edit(int id){
  var order = _orderRepository.Get(id);
  // check that order is not null and throw the appropriate exception etc
  return View(order);
}
Christian Dalager