Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the value of a Html.Hiddenfor

I have a form, to submit a bid.

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "Login" }))
{
    @Html.ValidationSummary(true, "Gelieve alle velden in te vullen.")

    @Html.LabelFor(m => m.Bid)<br /> 
    @Html.TextBoxFor(m => m.Bid)<br />  
    @Html.LabelFor(m => m.Name)<br /> 
    @Html.TextBoxFor(m => m.Name)<br />    
    @Html.LabelFor(m => m.Email)<br /> 
    @Html.TextBoxFor(m => m.Email)<br /> 
    @Html.HiddenFor(model => model.Car_id, new { value = ViewBag.car.id })
    <input type="submit" value="Bied" class="button" />
}

And I want to set the value of the hiddenfor to the id of the car (I get it with the viewbag), but it doesn't work as seen here:

<input data-val="true" data-val-number="The field Car_id must be a number." data-val-required="Het veld Car_id is vereist." id="Car_id" name="Car_id" type="hidden" value="" />    <input type="submit" value="Bied" class="button" />

What is the correct way of doing this? Or are there other ways of passing a value to my code? I just need the Car_id in the Postback method..

like image 211
Lonefish Avatar asked Jan 12 '14 13:01

Lonefish


People also ask

What does HTML HiddenFor do?

It creates a hidden input on the form for the field (from your model) that you pass it. It is useful for fields in your Model/ViewModel that you need to persist on the page and have passed back when another call is made but shouldn't be seen by the user.

What is HTML DisplayFor?

DisplayFor() The DisplayFor() helper method is a strongly typed extension method. It generates a html string for the model object property specified using a lambda expression.

How can set hidden field value in jQuery ASP NET MVC?

In jQuery to set a hidden field value, we use . val() method. The jQuery . val() method is used to get or set the values of form elements such as input, select, textarea.


2 Answers

even thought what Raphaël Althaus said is correct using the hard coded string is always a pain during refactoring. so try this

@{
   Model.Car_id = ViewBag.car.id;
}

@Html.HiddenFor(model => model.Car_id)

by this way it will still be part of your model and lot more cleaner.

like image 148
Anto Subash Avatar answered Nov 16 '22 03:11

Anto Subash


either Car_id is not a part of your model, then can't use HiddenFor, but have to use Hidden

something like

@Html.Hidden("Car_id", ViewBag.car.id)

assuming you've got something in ViewBag.car.id, the error you get seems to mean that there's nothing in there.

or it's part of your model and you shouldn't need a ViewBag. You should just set its value in the action related to that View.

like image 39
Raphaël Althaus Avatar answered Nov 16 '22 03:11

Raphaël Althaus