Html.BeginForm RouteValueDictionary vs Html.Hidden

What is the difference between these two ways 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)
}

      

Thank.

+3


source to share


4 answers


If you are using a submit button to submit a form, both approaches will be the same.

<input type="submit" value="submit" />

      

But if you want to use AJAX to submit the form eg. using jQuery then serialize the form. You need to use the second approach.

$.ajax({
   type: "POST",
   url: '/Controller/Action',
   data: $('form').serialize()
});

      



Update

If you use route values, it becomes a request parameter and is available in Request.QueryString["key"]

. If you are using hidden input, it will be available in Request.Form["key"]

.

Both are also available if you provide a parameter.

public ActionResult Action(string key)

      

0


source


The first approach uses the FormExtensions.BeginForm method , which adds values ​​to the form's submit url:

<form action="/ControllerName/ActionName?orderId=<Model.orderID>&productId=<Model.productID>" action="post">

      



The parameters here can be retrieved from the route parameters collection.

The second approach will simply add two hidden fields that can be bound to the model object passed to and from the controller action.

+2


source


The first uses the RouteValue dictionary, which adds these values ​​to the URL of the form posts. (These will be added as query string values ​​unless you have a corresponding route rule in which they will be added as "... / orderId / productId".) This makes the parameters more like GET.

The second adds input elements to the form in the DOM, which will then be truly POST-ed as form data for the action.

+1


source


On the first approach:

The object route values ​​will be sent to the postcontroller as a query string: "

<form action="/ControllerName/ActionName?orderId=1&productID=2" method="post"></form>

      

but with the second approach, you can get the values orderId

and productID

the model in the post-controller.

+1


source







All Articles