dubs
dubs

Reputation: 6521

Should MVC Controller GET actions use parameters

I'm considering simplifying my MVC controller actions.

Any thoughts on whether all GET actions should acquire their values using the RouteData.Values instead of taking parameters?

Upvotes: 2

Views: 472

Answers (1)

m0sa
m0sa

Reputation: 10940

You don't need to use RoutaData.Values if you setup your routes correctly, the default model binder does this for you. Behold the default route from global.asax:

routes.MapRoute(
   "Default", 
   "{controller}/{action}/{id}", 
   new { controller = "Default", action = "Index", id = UrlParameter.Optional } 
            );

So you can create an action like this:

 public ActionResult SomeAction(int id) {
   // in case of url '/MyController/SomeAction/1' id == 1
 }

You don't need to use RoutaData.Values at all, you just need to setup your routes correctly.. Why on Earth would you want to use something like this: (?!)

 public ActionResult SomeAction() {
   int id;
   if(int.TryParse(RoutaData.Values["id"] + "", out id))
   {
     // ...
   }
 }

Other arguments against this "pattern":

  • complicated unit testing of such controller classes / actions
  • circumvention of the model binding phase (pointed out by Ryan)
  • circumvention of the model validation phase

Upvotes: 3

Related Questions