tags:

views:

37

answers:

3

Is there a way to force the request router to disambiguate controller actions based on method signatures?

for instance(in a controller):

[HttpPost]
public ActionResult MyAction(FormCollection f) {
    //do stuff with big form and return viewresult
    return View();
}

[HttpPost]
public JsonResult MyAction(string foo, string bar, bool baz) {
    //separate method to handle just the ajax stuff
    return Json();
}

I know I can use Request.IsAjaxRequest() in the first method and use that if/then branch to decided my action... but it feels cleaner to leave them separate methods. Not to mention I'd have to cast out the boolean 'baz' (and any other of the non-string types). I have a legitimate reason to use the FormCollection at times or else I'd just keep the JsonResult version around. (the formcollection allows editing of 'many' items while the Json parametrized version just edits a single item)

I could just use different method names too... (probably what I'll do if I can't do what I want)

I tried setting the return type of the 1st method explicitly to ViewResult and ensuring the client sent only accept: application/json headers, but doesn't seem to matter as I keep getting exceptions about the method signatures being ambiguous. Is there a way to force the behavior I want?

A: 

The MVC framework does not use the method's return type to filter methods.

If you really want to do this, you can write your own ActionFilter.

SLaks
A: 

From what I've experienced, ASP.NET MVC does not really enjoy trying to overload methods. You'd be better off leaving it as one method with an if/else, or making another Action that responds specifically to the Ajax request.

Andrew Burgess
A: 

I agree that it would be cleaner to be able to choose an action based on the return type. You could implement your own IActionInvoker class to do this.

Ryan
this seems like a useful suggestion... However, it seems like it would over-complicate things a bit though. Like fighting the framework a bit too much...
Chris Hamant
These extensibility points exist for a reason.
Ryan
I do like the action filter suggestion though. This is what we do for all our tabular data. The action itself returns a tabular model. Then an action filter looks at the request to determine if the table should be rendered as Json (for jqgrid), Html, Csv, or Pdf. We then transform the tabular model to get the result (use the visitor pattern here). It's very useful because the action doesn't ever have to worry about the request; it just returns data.
Ryan