Basically it is the same principle of creation, but some more details need to be observed:
- The identifier of the Model original needs to exist somehow;
- You will need to bring from the bank the Model twice: once to fill the Viewmodel and another to update it.
An editing cliché of a Model Produto
two-property, Id
and Nome
, would be something like:
public async Task<ActionResult> Editar(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Produto produto = await db.Produtos.FindAsync(id);
if (produto == null)
{
return HttpNotFound();
}
var produtoViewModel = new ProdutoViewModel
{
ProdutoId = produto.ProdutoId,
Nome = produto.Nome
};
return View(produtoViewModel);
}
The construction of its View will be exactly the same as the construction using a Model. What changes is only the note @model
:
@model MeuProjeto.ViewModels.ProdutoViewModel
In the POST
:
[HttpPost]
public async Task<ActionResult> Editar(ProdutoViewModel viewModel)
{
if (ModelState.IsValid)
{
var produto = db.Produtos.FirstOrDefault(p => p.ProdutoId == viewModel.ProdutoId);
if (produto == null)
{
return HttpNotFound();
}
produto.Nome = viewModel.Nome;
db.Entry(produto).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(viewModel);
}
Advantages of the approach:
- Security: You do not directly expose your Models on forms;
- Flexibility: more specific validation rules without necessarily impacting the Model.
Disadvantages of the approach:
- Complexity: your system will inevitably get bigger and more complex, and maintenance will be more difficult;
- Rework: extend a Model will mean extending all the Viewmodels associated with Model.
Even though I have several models as in this question of mine, would work that way?
– Érik Thiago
It’s not working out. =(
– Érik Thiago
I think it’s time for another question.
– Leonel Sanches da Silva
I’ve already created the question!
– Érik Thiago