Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.HiddenFor with preset value

Tags:

asp.net-mvc

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

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

But when execute my code i get the error that model.idv and modele.etat are null.
This is seconde part no sloved till now :
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 view page :

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

So when i click on submit button the model.idv is set again on null value

like image 882
Chlebta Avatar asked Apr 27 '12 22:04

Chlebta


1 Answers

The correct way to set a preset value is to pass it in via the model (MVC appears to ignore the "value" parameter if you set it). To accomplish what you're looking for, in your action:

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

Then you don't have to do anything in your view except have:

<%: Html.HiddenFor( model => model.idv ) %>
<%: Html.HiddenFor( model => model.etat ) %>
like image 86
Ethan Brown Avatar answered Oct 04 '22 15:10

Ethan Brown