Capture checkboxes marked in a View

Asked

Viewed 35 times

0

I’m listing my objects through a ViewBag sent to the View, and for each item there is a checkbox, and for each contract there is an Id:

@foreach (var item in ViewBag.Contratos)
{
<tr>
  <td>
    <input type="checkbox" class="form-check-input" id="CheckBoxPessoa">
  </td>
</tr>
}

How can I capture the contract id of each checkbox checked? I want to send this "list" of Id’s as a parameter for a controller method.

  • How is your Controller and how are you doing the post for her? Correct question with the correct code snippet from your view

1 answer

0

I’m not sure I understand your question, but come on.
For this first you have to put the value in the value of the input

@{int i = 0;}
@foreach (var item in ViewBag.Contratos)
{
<tr>
  <td>
    <input type="checkbox" class="form-check-input" name="entity[@i].id" value="@item.id">
  </td>
</tr>
}

In the controller you would have:

public ActionResult NomedoController(entity List<Entity>) {}

Read Entity as your class.

Follow an example below:

@model List<WebMetas.ViewModels.ProdutoMetaViewModel>
@{
    ViewBag.Title = "Incluir - Meta";
}
@using (Html.BeginForm("Create", "Meta", FormMethod.Post))
{
@Html.AntiForgeryToken()
<table class="table table-bordered table-striped table-hover table-responsive dt-responsive">
    <thead>
        <tr>
            <th class="text-center col-sm-2">Descrição</th>
            <th class="text-center col-sm-2">Qtde</th>
        </tr>
    </thead>
    <tbody>
        @{
            var index = 0;
            foreach (var produto in Model)
            {
                <tr>
                    <input type="hidden" name="[@index].ProdutoId" id="[@index].ProdutoId" value="@produto.ProdutoId" />
                    <td>
                        @produto.Descricao
                    </td>
                    <td class="text-right">
                        <input type="text" class="text-right" name="[@index].Qtde" id="[@index].Qtde" />
                    </td>
                </tr>
                index++;
            }
        }
    </tbody>
</table>
<button type="submit" class="btn  btn-primary"><span class="glyphicon glyphicon-floppy-saved"></span> Salvar</button>
}

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IEnumerable<ProdutoMetaViewModel> produtos)
{
   //Implementar
} 

Follow a reminder that can help you: link

Browser other questions tagged

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