Data is lost in the Controller - View - Controller process

0

I told you that I have 2 controllers, one for the GET and another for the POST that I am going to edit so that it is easier to understand:

// GET: Compras/Create
public ActionResult Create(int id)
    {

       ComprasCreateModel compra = new ComprasCreateModel();

       compra.ClienteId = id;
       compra.NombreCliente = db.Clientes.Find(id).Nombre;

       return View(compra);

    }


// POST: Compras/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ComprasCreateModel compra)
    {

        if (compra.ClienteId == 0)
          return View(A);
        else
          return View(B);

    }

And it happens, that my Vista Create presents a form to fill:

model.Age

model.Telephone

Therefore, the only thing that changes the model in the View is those properties. And when you click on the submitButton the POST driver is called.

But if from the GET a purchase model was passed with the properties ClientId and CustomerName, why is the final result that shows me the View A?

That is, the POST of Create arrives purchase.ClientId with value 0, and buys.CustomerName with value null.

It is as if the form is creating a new new model with the data that was filled, thus forgetting the previous model that was passed as a parameter to the View.

What is it that I am not yet understanding about this?

    
asked by Edu 25.11.2018 в 07:20
source

1 answer

1

For the complete model to be part of the model binding you must assign all the properties to the html object that are part of the body of the request

@Html.BeginForm("xxController", "Create", Method.Post){

   @Html.HiddenFor(m=>m.NombreCliente) 
   @Html.HiddenFor(m=>m.ClienteId) 

   @Html.LabelFor(m=>m.NombreCliente) 
   @Html.TextBoxFor(m=>m.Edad)
   @Html.TextBoxFor(m=>m.Telefono)

   <input type="submit" value="crear" />
}

If for example you define a @Html.LabelFor() this value does not apply in the request and the value will not be sent to the server for the model binding, so the @Html.HiddenFor()

is used     
answered by 25.11.2018 / 22:54
source