Mr_LinDowsMac
Mr_LinDowsMac

Reputation: 2702

Set values of excluded values in Model Binding

In a MVC5 ASP.NET application with Entity Framework 6 I have the following Create method:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "folio,fecha,almacen,cliente,plaza,usuario,id_factura")] facturas_prueba facturas_prueba)
{
     if (ModelState.IsValid)
     {
          db.facturas_prueba.Add(facturas_prueba);
          db.SaveChanges();
          return RedirectToAction("Index");
     }

     ViewBag.almacen = new SelectList(db.CATALMA, "COD_ALM", "NOM_ALM", facturas_prueba.almacen);
     ViewBag.cliente = new SelectList(db.CATCTES, "COD_CTE", "NOM_CTE", facturas_prueba.cliente);
     ViewBag.usuario = new SelectList(db.FACPARU, "cod_usu", "cod_Alm", facturas_prueba.usuario);
     ViewBag.plaza = new SelectList(db.PLAZAS, "PLAZA", "LAST_COD_CTE", facturas_prueba.plaza);
     return View(facturas_prueba);
}

As you can see, by default is using a [Bind(Include = .As far I know, I could use to only include request parameters that I want. So, I just want folio, fecha, almacen and cliente. The others fields I would like to manually set them (for the moment, hardcoded values) and delete any field related to them in the view (because we don't users to put those values). How is the MVC-way to this...?

Upvotes: 0

Views: 108

Answers (1)

D Stanley
D Stanley

Reputation: 152511

How is the MVC-way to this...?

Use a different model type for your view and your persistence layer. Your "ViewModel" class would contain only the types/properties that are exposed in the view (or hidden but required for the view to function properly).

When the data is submitted for an add/update - the existing fields are retrieved from the source, merged with the submitted data, and then persisted back.

Upvotes: 1

Related Questions