Maturano Maturano - 2 months ago 12
ASP.NET (C#) Question

Get the selected Items in ASP.Net MVC

I'm building a View where the user can select some companies and after selecting some companies I can click on a buttong and do something.
The problem is that I couldn't bind the selected companies in the ViewModel.

Here are what I have:

The ViewModel:

public class ParametrosPesquisaViewModel
{
public ParametrosPesquisaViewModel()
{
Empresas = new List<EmpresaViewModel>();
}

public IList<EmpresaViewModel> Empresas { get; set; }
}


The Controller:

Get

public ActionResult Pesquisa()
{
ParametrosPesquisaViewModel parametros = new ParametrosPesquisaViewModel();
var empresas = _empresaAppService.BuscarEmpresasValidas();

foreach (EmpresaViewModel empresa in empresas)
{
//Simulando a empresa logada
empresa.Selecionada = empresa.empresa == 1;
parametros.Empresas.Add(empresa);
}

return View(parametros);
}


Post

public ActionResult Pesquisa(ParametrosPesquisaViewModel parametros)
{
//Do something
}


Html:

@model LMX.RecuperadorCupomFiscal.Application.ViewModels.ParametrosPesquisaViewModel

@using (Html.BeginForm("Pesquisa", "RecuperadorCupomFiscal", FormMethod.Post))
{
... skipping some html code
<table class="table table-striped table-hover">
<thead>
<tr>
<th>
<label for="Empresa">Empresa(s):</label>
</th>
<th>
<label for="cidade_emp">Cidade</label>
</th>
<th>
<label for="estado_emp">Estado</label>
</th>
</tr>
</thead>
<tbody>
@foreach (var empresa in Model.Empresas)
{
<tr>
<td>
@Html.CheckBoxFor(model => empresa.Selecionada)
@Html.DisplayFor(model => empresa.NomeEmpresaCodigo)

</td>
<td>
@Html.DisplayFor(model => empresa.cidade_emp)
</td>
<td>
@Html.DisplayFor(model => empresa.estado_emp)
</td>
</tr>
}
</tbody>
</table>


}


In the Post ActionResult, the parametros.Empresas is not getting the binding.
What is the best approach for this case?

Answer

The way you are generating checkboxes, model binder won't be able to bind submitted data. Instead, try rewriting your loop this way:

@foreach (var i = 0; i < Model.Empresas.Count; i++)
{
    <tr>
        <td>
            @Html.CheckBoxFor(model => Model.Empresas[i].Selecionada)
            @Html.DisplayFor(model => Model.Empresas[i].NomeEmpresaCodigo)
        </td>
        <td>
            @Html.DisplayFor(model => Model.Empresas[i].cidade_emp)
        </td>
        <td>
            @Html.DisplayFor(model => Model.Empresas[i].estado_emp)
        </td>
    </tr>
}