Question

I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions.

For example, I have a route like this:

routes.MapRoute(
            "TestController-TestAction",
            "TestController.mvc/TestAction/{paramName}",
            new { controller = "TestController", action = "TestAction", id = "TestTopic" }
            );

And a form declaration that looks like this:

<% using (Html.Form("TestController", "TestAction", FormMethod.Get))
   { %>
     <input type="text" name="paramName" />
     <input type="submit" />
<% } %>

which renders to:

<form method="get" action="/TestController.mvc/TestAction">
  <input type="text" name="paramName" />
  <input type="submit" />
</form>

The resulting URL of a form submission is:

localhost/TestController.mvc/TestAction?paramName=value

Is there any way to have this form submission route to the desired URL of:

localhost/TestController.mvc/TestAction/value

The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript.

Was it helpful?

Solution

Solution:

public ActionResult TestAction(string paramName)
{
    if (!String.IsNullOrEmpty(Request["paramName"]))
    {
        return RedirectToAction("TestAction", new { paramName = Request["paramName"]});
    }
    /* ... */
}

OTHER TIPS

In your route, get rid of the {paramName} part of the URL. It should be:

TestController.mvc/TestAction

As that is the URL you want the request to route to. Your form will then post to that URL. Posted form values are mapped to parameters of an action method automatically, so don't worry about not having that data passed to your action method.

My understanding is that this is how HTML works. If you do a <form url="foo" method="get"> and post the form, then the form will post foo?

param1=value1&...&paramn=valuen

It has nothing to do with MVC.

Besides, what part of REST does that URL violate? It's not a pretty URL, but by strict definition of REST, it can be RESTful. REST doesn't specify that query parameters have to be in an URL segment. And in this case, those are query parameters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top