Reputation: 8651
What's the difference between the two methods below to pass parameters to a controller action? When should I use one or the other?
First approach:
@using (Html.BeginForm("ActionName", "ControllerName", new {orderId = Model.orderID, productId = Model.productID}, FormMethod.Post))
{
...
}
Second approach:
@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post))
{
...
@Html.Hidden("orderId", model.orderID)
@Html.Hidden("productID", model.productID)
}
Thanks.
Upvotes: 3
Views: 1405
Reputation: 14640
If you use submit button to submit the form both approaches would be the same.
<input type="submit" value="submit" />
But if you want to use AJAX to submit the form, e.g. using jQuery, then serialize the form. You need to use second approach.
$.ajax({
type: "POST",
url: '/Controller/Action',
data: $('form').serialize()
});
If you use route values it will become query parameter and available in Request.QueryString["key"]
. While if you use hidden input, it will be available in Request.Form["key"]
.
Both of them are also available if you provide parameter.
public ActionResult Action(string key)
Upvotes: 0
Reputation: 18873
With first approach :
Object Route Values will go to post controller as querystring as shown :"
<form action="/ControllerName/ActionName?orderId=1&productID=2" method="post"></form>
but with second approach you can get orderId
and productID
values from model at post controller.
Upvotes: 1
Reputation: 3203
The first approach is using FormExtensions.BeginForm method override which is appending values to the form submit url:
<form action="/ControllerName/ActionName?orderId=<Model.orderID>&productId=<Model.productID>" action="post">
Parameters from here could be retrieved from the route parameters collection.
Second approach will simply add two hidden fields which could be bound to the model object passed in and out of controller action.
Upvotes: 2
Reputation: 1082
The first is using the RouteValue dictionary, which will add those values to the URL the form posts to. (They will be added as query string values, unless you have a matching Route rule specified at which point they would be added as '.../orderId/productId'.) This makes the parameters more GET-like.
The second adds input elements to the form in the DOM, which will then be truly POST-ed as form data to the action.
Upvotes: 1