How to do Edit action with view model?

Asked

Viewed 184 times

1

I’m trying to do in my project the editing part of the data that was registered. Well, the data log part is working fine, but now I need to edit this data. Before, I looked around the web to see what I could find about it. I found link no Sous. Only I didn’t understand the code right...

Could someone help me?

1 answer

1


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.