views:

99

answers:

1

MVC encourages RESTful URL's, yet HTML forms by nature append the data in query string values. My action takes "text" as a string parameter. And my form is:

<% using(Html.BeginForm("Action", "Controller")) { %>
  <%= Html.TextBox("text") %>
  <input type="submit" value="submit" />
<% } %>

My action is:

public ActionResult Action(string text)
{
    ...
    return toInnocence;
}

There are two distinct URL's that your action can map to:

  1. ~/Controller/Action/textvalue thanks to your route map {controller}/{action}/{text}
  2. ~/Controller/Action?text=textvalue when submitted from a form

My question is:

How can I differentiate between two forms and do a redirect in the latter case? The second form breaks RESTful principle. What's the best practice there? I don't want to query RouteData.Values collection because it breaks the whole purpose of mapping request parameters to function arguments in a natural, straightforward way. This is a very basic scenario I expect MVC to handle this nicely.

The second form doesn't map to "text" parameter in the controller action. Why? How can I create overloaded versions of the same action then? Do I have to create a new action and use it for form submissions? Of course I can workaround all these but at the same time I'm afraid of missing the big picture somewhere.

It looks like people are getting along with these at ease so I feel like I'm the only one who is confused by route values against query strings.

EDIT: I looked at how Wikipedia does this. It uses separate actions for "form getter" and the actual restful URL and redirects from one to another as needed. I guess that would be the best way of doing it.

+3  A: 

The default operation of your browser is to put the values in the GET form in the query string. They will both resolve to a route of and go to the same action.

{ controller = "Controller", "Action", id = null, text = "textvalue" }

Because of the presence of the default route, this will correctly resolve.

The only way I can think of to do what you're asking is to change the form. Instead of submitting a "GET" request, submit as a PUT because you don't need a POST (you can do this with JS, with a friendly degrade to POST) and redirect to a GET.

Jarrett Meyer
So the best practice is to use separate actions for form submissions and URLs?
ssg
Check out #13 on Post-Redirect-Get: http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspxIMO, a post is a bit much. You can use JS to create a put request. (Put requests will not create the typical browser "Resubmit POST data?" popup.)
Jarrett Meyer