How do I pass a View value to the Controller in Asp.net core?

Asked

Viewed 189 times

1

I want to go from View

<table style="width:100%">
<tr>
    <th>Serviço</th>
    <th>Data</th>
    <th>Feito</th>
</tr>
@{
    foreach (var item in ViewBag.servico)
    {
<tr>
    <td>@item.Servico</td>
    <td>@item.Data</td>
    <td>@item.Feito</td>
    <td>Editar</td>
    <td>
        <form action="/Tarefas/Remover" method="post">
            @{
                var tarefa = item;
             }
            <input type="submit" value="Excluir" />
        </form>
    </td>
</tr>
    }
}

For the controller:

[HttpPost]
public IActionResult Remover(Tarefa tarefa)
{
    using (var item = new AgendaDBContext())
    {
        item.Servicos.Remove(tarefa);
        item.SaveChanges();

    }
    return View("Lista");
}
  • Already tried passing only the controller in Action? <form action="/Tarefas" method="post">

  • <form action="/Tasks/Remove" method="post"> I’m going through post, I just don’t know how to pass the object

  • 1

    Your fields need to be inside the form and attribute name fields need to be the same properties names that refer to their model Tarefa.

  • Include the structure of the entity Tarefa in your question

1 answer

0


RESOLVED * I’m just not sure if this would be a bad practice, I’m sending the id to controller by creating a new task instance and associating it with an id and sent to Entity to delete.

Creating a new instance is a bad practice ?

<table style="width:100%">
<tr>
    <th>Serviço</th>
    <th>Data</th>
    <th>Feito</th>
</tr>
@{
    foreach (var item in ViewBag.servico)
    {
<tr>
    <td>@item.Servico</td>
    <td>@item.Data</td>
    <td>@item.Feito</td>
    <td>Editar</td>
    <td>
        <form action="/Tarefas/Remover" method="post">
                <input type="hidden" name="id" value="@item.Id" />
            <input type="submit" value="Excluir" />
        </form>
    </td>
</tr>
            }
}

Controller:

[HttpPost]
    public IActionResult Remover(int id)
    {            
        using (var item = new AgendaDBContext())
        {
            Tarefa tarefa = new Tarefa();
            tarefa.Id = id;
            item.Servicos.Remove(tarefa);
            item.SaveChanges();

        }
        return RedirectToAction("Lista", "Tarefas");
    }
  • works, the Hidden field is what a <asp for=... could render to the case or could be the button itself for example... the practice is not the best, it makes no sense to have one form per line. with other approaches and structure, you can implement this functionality more easily and with more features, such as the multiple selection option for removal

Browser other questions tagged

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