Html.HiddenFor with a given value

This part was disabled thanks to Ethan Brown I want to set the value of my Html.HiddenFor with the given value. This is my code:

 <%: Html.HiddenFor(model => model.idv, new { @value = ViewBag.id })%> <%: Html.HiddenFor(model => model.etat, new { @value = "false" })%> 

But when I run my code, I get an error that model.idv and modele.etat are null.
This is the second part that has not been shared so far:
This is my action:

 public ActionResult Reserver(string id) { var model = new Models.rservation { idv = id, etat = false }; return View(model); } [HttpPost] public ActionResult Reserver(Models.rservation model) { if (ModelState.IsValid) { entity.AddTorservation(model); entity.SaveChanges(); return View(); } else { return View(model); } } 

And this is my browse page:

 <% using (Html.BeginForm("Reserver", "Home", FormMethod.Post, new { @class = "search_form" })) { %> //some code textbox to fill <input type="submit" value="Create" /> <% } %> 

Therefore, when I press the submit button, model.idv is set to zero again

+7
source share
1 answer

The correct way to set a predefined value is to pass it through the model (MVC seems to ignore the value parameter if you set it). To accomplish what you are looking for in your action:

 public ActionResult MyAction() { var model = new MyModel { idv = myPresetId, etat = false }; return View( model ); } 

Then you do not need to do anything if you have:

 <%: Html.HiddenFor( model => model.idv ) %> <%: Html.HiddenFor( model => model.etat ) %> 
+14
source

All Articles