How to do action edit with view model?

1

I am trying to do in my project the editing part of the data that have been registered. Well, the data registration part is working fine, but now I need to edit this data. Before, I've been looking around the web to see what I could find out about it. I found link in SOus. I just can not understand the code ...

Could anyone help me?

    
asked by anonymous 07.06.2016 / 04:49

1 answer

1

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 .
07.06.2016 / 05:39