tags:

views:

261

answers:

1

Basically I have a bunch of submission forms that gather data in a generic way -> serialize the input / value pairs to a CSV file. I'd like to add new submission pages without having to write a new controller action (the idea being I wouldn't have to compile and deploy a new assembly). So, here's my thinking:

http://foobar.com/Submission/Contact
http://foobar.com/Submission/Apply

both should route to the SubmissionController.Handle() method. The Handle method will show the view for the appropriate action:

return View("Contact");
// or
return View("Apply");

The views would both have their form's actions as "/Submission/Handle" and the controller would have:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Handle(FormCollection inputs)

So a) how do I route both the actions Contact and Apply to Handle and b) how do I query from within the SubmissionController for the action name so I can do:

var viewName = GetActionName();
return View(viewName);

Obviously I'm a n00b to ASP.NET MVC ... so if there's a better method, please let me know.

A: 

You would have to write a custom route. For example, in global.asax before the default route:

// Submission/*
routes.MapRoute(
      "Submission",
      "Submission/{method}", 
      new { controller = "Submission", action = "Handle", method = "" }
      );

You can add anything within brackets, and that will be the key to the route's value in the RouteValueDictionary. Note that controller and action are conventions used within ASP.NET MVC.

The way you have it stated: To access this new key called 'method' in your controller, you'd do something like:

string methodName = RouteData.Values["method"];

Then, I guess do a switch for each of your methods.

Perhaps and easier way: Instead of doing a swtich to return a specific view, what I'd do is:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Handle(FormCollection inputs)
    {
        ViewData["method"] = RouteData.Values["method"];

        return View();
    }

add the methodName to ViewData. and return the HandleView. Then, create a partial for each form type. In the HandleView, put:

<% Html.RenderPartial(ViewData["method"]); %>

That way, you don't have a bunch of hard-coded routes to handle. But, you'll have to handle errors and incorrect methods being passed to the route.

Jim Schubert
I definitely like the PartialView strategy. Thanks for the help!
xanadont
no problem. You can find a lot more information about routing (constraints, custom routes, etc) at http://www.asp.net/learn/mvc/ and if you prefer following videos: http://www.asp.net/learn/mvc-videos/
Jim Schubert