Can't figure out How to decide when to use Hidden () and when to use HiddenFor ()

I am following the book and here is the code:

@using (Html.BeginForm("RemoveFromCart", "Cart"))
{
    @Html.Hidden("ProductId", line.Product.ProductID)
    @Html.HiddenFor(x => x.ReturnUrl)
    <input class="btn btn-sm btn-warning" type="submit" value="Remove" />
}

      

And here is his explanation why he used Hidden

insteadHiddenFor

enter image description here

but still I cannot understand the wiring behind her that he is talking about. Can you elaborate on this in more detail?

public RedirectToRouteResult RemoveFromCart(Cart cart, int productId, string returnUrl)

      

+3


source to share


3 answers


You need to remember that these helpers are just ways to generate HTML markup.

An example of the generated markup:

@Html.Hidden("ProductId", line.Product.ProductID)

      

Forms:  <input type="hidden" name="ProductId" value="5" />

@Html.HiddenFor(x => x.Product.ProductID)

      



Forms:  <input type="hidden" name="Product_ProductId" value="5" />

The controller defines a parameter with a name productId

. For model binding to work, the name

hidden input value must match the argument name.

Product_ProductId

will not match the specified argument productId

for the RemoveFromCart

Controller action .

It's worth noting that model binding is case insensitive. This way your hidden input value productId

will be bound to the parameter RemoveFromCart

productId

.

+3


source


in yours RemoveFromCart(Cart cart, int productId, string returnURL)

you have an explicit variable in particular int productId

. One would expect the HTML to specify a field "ProductId

to fill in the value. If you use the helper Html.HiddenFor

, it generates a field with a fully qualified variable name , resulting in an HTML field named "Product_ProductID"

. The model linker will not be able to match HTML with this field name with the correct parameter in the function call.



+1


source


Use HiddenFor if the ViewModel property just needs to be passed through the view without any complicated processing.

The Hidden method is the more common way to bind data and is not necessarily associated with your ViewModel, but with the form.

The "HiddenFor" method is simply an automated way to directly bind ViewModel properties.

+1


source







All Articles