Set the value of a Html.Hiddenfor

Lonefish picture Lonefish · Jan 12, 2014 · Viewed 36.3k times · Source

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..

Answer

Anto Subash picture Anto Subash · Jan 12, 2014

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.