I am开发者_JAVA百科 adding a search box to a Asp Mvc.
This is html for the form:
@using (Html.BeginForm("Query", "Search", FormMethod.Get))
{
<input type="text" name="q" />
<input type="submit" value="Seach" />
}
and I added this route
routes.MapRoute("Search", "q={query}",
new { controller = "Search", action = "Query" });
I would like the form to generate a url that looks like http://localhost:####/q=value in textbox
.
Is it possible to change the way MVC generates the url? This is currently what I get:
http://localhost:50916/Search/Query?q=value in textbox
According to RFC 3986 the =
sign is a reserved character used to delimit parameters and parameter values and you shouldn't use it at this part of the URI. The closest you might get is http://localhost:####/?q=value
.
As a matter of fact you could use a route like this as an incoming URL and ASP.NET MVC will correctly parse it and dispatch to the correct controller action. The problem is with the <form>
tag. There are two possible verbs: GET and POST. If you use POST parameters entered in the form will be sent in the request body and not shown in the URL. If you use GET according to the specification, user agents will send a request by appending key/value pairs of input fields to the action of the form after appending ?
.
So you cannot achieve the desired effect unless you use some javascript which would handle the onsubmit
event of the form, cancel the default submission and change the window.location
to the desired format. The question is: do you really need to go that far?
You could just use the standard HTML form tag instead of the HTML helper, if you need more specific control over the target URL.
精彩评论