8

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

Lonefish
  • 647
  • 2
  • 11
  • 32

3 Answers3

20

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.

Anto Subash
  • 3,140
  • 2
  • 22
  • 30
  • 1
    Furthering this thinking, I did away with ViewBag entirely and set the Id in the controller. I was already passing my model so it seemed silly to pass both only to combine them in the view. – Rich Nov 24 '15 at 14:23
6

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.

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • It is part of my model, but it isn't set yet. The form is to insert a bid, but I need the car id to insert it too, and I can't ask a user to insert an id... I'll try Hidden! Thanks! – Lonefish Jan 12 '14 at 13:14
  • It works now, but how do I catch it in my controller? Since it's not part of my model anymore? – Lonefish Jan 12 '14 at 13:20
2
@Html.HiddenFor(model => model.Car_id, htmlAttributes: new { @Value = ViewBag.Car_id })
Alvaro Rodriguez Scelza
  • 3,643
  • 2
  • 32
  • 47
  • When you do this, check the html for the hidden tag on the client side. Now you will have "Value" and a "value" tags. One starts with lower and one starts with upper case. – Robert Smith Feb 28 '23 at 16:05