BeginForm with null controller and action missing parameters
I want to add an ID attribute to my form, so I follow the answer here
Originally my code was using:
Html.BeginForm()
and the output looks like this:
<form action="/Controller/Action?Id=5" method="post">
but when I replace the Html.BeginForm() with:
Html.BeginForm(null, null, FormMethod.Post, new { @Id = "blah" });
the output form is missing the parameter:
<form action="/Controller/Action" method="post">
It all seems to just work "magically" if I replace the BeginForm with <form action="" method="post">
but I'd like t开发者_JAVA技巧o understand what's going wrong with the helper version.
You're trying to use this version of the method, correct?
<ExtensionAttribute> _
Public Shared Function BeginForm ( _
htmlHelper As HtmlHelper, _
actionName As String, _
controllerName As String, _
method As FormMethod, _
htmlAttributes As Object _
) As MvcForm
Couple of things:
htmlAttributes is the attributes of your form tag, and has nothing to do with the ?Id=5 part of your query string.
Why is your "Id" variable prefixed with an '@' symbol anyway? But again, because of #1 above, it doesn't matter. You don't need to use this.
I'm guessing that Html.BeginForm() "just works" because you are viewing this as the result of a GET request on /Controller/Action/5. The default POST, then, would have the same URL.
The same goes if you do -- in HTML, when you specify the empty string ("") for the URI in the action parameter, it will interpret that as the current URI. See RFC 2396:
4.2. Same-document References
A URI reference that does not contain a URI is a reference to the current document. In other words, an empty URI reference within a document is interpreted as a reference to the start of that document, and a reference containing only a fragment identifier is a reference to the identified fragment of that document. Traversal of such a reference should not result in an additional retrieval action. However, if the URI reference occurs in a context that is always intended to result in a new request, as in the case of HTML's FORM element, then an empty URI reference represents the base URI of the current document and should be replaced by that URI when transformed into a request.
Does this answer your questions?
Edit: Ah, I see what you're asking now. I'm not sure why passing null doesn't include the same URI. If you explicitly include the action name and controller name, does it work? I've done it this way in MVC applications and it has worked properly.
精彩评论