开发者

How can I learn to stop worrying and love ASP.NET MVC Forms?

开发者 https://www.devze.com 2022-12-14 05:59 出处:网络
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:

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消