This was sent to me by a friend at work, Andy Pickett, and I thought it deemed worthy of Brain.Save:
Ok, I wanted to have these URLs both be valid:
1) http://localhost/ProposalGrid.mvc/display/2/15418
- Get the latest Active Proposal for borrower
2) http://localhost/ProposalGrid.mvc/display/2/15418/26
- Get the Proposal with ProposalId = 26 (assume borrowerid matches)
I think these may be common scenarios throughout CARRS given the way we’ve set up route masks (ignore for the moment that there are Primary Keys in our URLs ;) )
I wanted 2 different action methods (instead of a single action with a switch stmt):
A) public ActionResult Display()
B) public ActionResult Display(int id)
but by default mvc doesn’t like that and can’t figure out which method to call for the #2 URL above, it throws an ambiguous method exception at runtime (note: #1 works fine and always goes to (A)). So I found this on StackOverflow, and I think it makes some sense.
http://stackoverflow.com/questions/1045316/asp-net-mvc-ambiguous-action-methods
So I added and modified their RequireRequestValueAttribute to check if the Route has data for “id” (has to be an positive int per route mapping). And then by adding it to the action method like so:
[RequireRequestValue("id")]
public ActionResult Display(int id)
then URL (1) gets routed to Action (A), and URL (2) goes to (B). So far it works the way I want it to, but it may not be the preferred “MVC way”. If there’s alternatives out there please let me know. Otherwise, feel free to use this attrib for your own overloads.
No more then a few paragraphs of things I want to archive (instead of try to remember)
Tuesday, February 9, 2010
Subscribe to:
Posts (Atom)