Basically it's the same principle of creation, but some more details need to be observed:
- The original Model identifier must exist in some way;
- You will need to bring the Model from the database twice: once to populate the ViewModel and another to update it.
An editing cliché of a Model Produto
with two properties, Id
and Nome
, would look 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);
}
Building your View will be exactly the same as building it using a Model . What changes is just the annotation @model
:
@model MeuProjeto.ViewModels.ProdutoViewModel
No 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 approach:
- Security: you do not directly expose your Models in forms;
- Flexibility: more specific validation rules, without necessarily impacting Model .
Disadvantages of approach:
- Complexity: your system will inevitably become larger and more complex, and maintenance will be more difficult;
- Rework: Extending a Model will mean extending all ViewModels associated with the Model .