checkbox + Model + Controller. How to pick up selected rows?

Asked

Viewed 1,371 times

0

I’m sent to my model typed for a view and loaded the data into a table where I enclose a checkbox for each line. The user will select the items that matter to be later saved in the database. My doubt is precisely at this point. How do I send to controller the items. In addition to my data list I also send other information.

My model that’s the one:

public int Id { get; set; }
public string CodigoUsuario { get; set; }
public string NomeUsuario { get; set; }
public List<Fornecedor> ListaFornecedorViewModels { get; set; }

Man controller that’s the one:

public ActionResult UsuarioNovo() {
    UsuarioViewModel usuarioViewModel = new UsuarioViewModel();
    ViewData["Colaborador"] = _userLogado;
    return View(usuarioViewModel);
}
[HttpPost]
public ActionResult UsuarioNovo(UsuarioViewModel usuarioViewModel)
{
    if (usuarioViewModel.ListaFornecedorViewModels != null)
    {
        if (!string.IsNullOrEmpty(usuarioViewModel.FornecedorBusca)) {
            int iCnpj;
            var listFornecedor = new BuscaDadosFornecedorBo().BuscaRequisicaoFornecedorBo(usuarioViewModel.FornecedorBusca, "");
            usuarioViewModel.ListaFornecedorViewModels = listFornecedor;
        }
    }
    else
    {
        //Gravar Dados
    }
    return View(usuarioViewModel);
}

And this is my View:

@using (@Html.BeginForm()) {
<div class="linha">
    <div class="campo item small">
        @Html.LabelFor(model => model.NomeUsuario)
        @Html.EditorFor(model => model.NomeUsuario)
    </div>
</div>

<div class="linha">
    <div class="campo item small">
        @Html.LabelFor(model => model.SobrenomeUsuario)
        @Html.EditorFor(model => model.SobrenomeUsuario)
    </div>
</div>

<div class="panel-content">
    <div class="linha">
        <div class="campo item">
            @Html.LabelFor(model => model.FornecedorBusca)
            @Html.EditorFor(model => model.FornecedorBusca)
        </div>
        <input class="btn btn-primary" type="submit" value="Buscar" />
    </div>
</div>  

@if (Model.ListaFornecedorViewModels != null) {
    <div class="table-custom">
        <table cellpadding="0" cellspacing="0" border="0" class="dataTable display">
            <thead>
                <tr>
                    <th class="sorting_disabled" rowspan="1" colspan="1" aria-label=" " style="width: 10px;"> </th>
                    <th>Selecionar</th>
                    <th>CNPJ</th>
                    <th>RazaoSocial</th>
                    <th>Municipio</th>                                    
                </tr>
            </thead>

            <tbody>
                @foreach (var forn in Model.ListaFornecedorViewModels) {
                    <tr>
                        <td></td>
                        <td><input type="checkbox" value="@forn.Codigocnpj" name="chkForn"/></td>
                        <td>@forn.Codigocnpj</td>
                        <td>@forn.RazaoSocial</td>
                        <td>@forn.Municipio</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
}

}

I’ll need to give two post in the same action "New user"... The first to search for the list of suppliers and the second to send the data plus the selected list items. How am I gonna do that?


EDIT

I made the adjustments @Gypsy mentioned in the model and I’m using Begincollectionitem, but the selected one is always coming as false and the other fields as null. See the images:

Grid

And in my code it shows: codigo

What am I doing wrong?

  • Has already installed the Begincollectionitem?

  • And what that could help me Gypsy?

  • Solving your problem. If not, I put an answer.

  • I don’t know how to use what you mentioned. Please, I await your reply.

  • If you want the fields to go to the Controller, you need to turn them into @Html.EditorFor() or @Html.HiddenFor(), but I only recommend doing this for the Supplier ID. Not for all fields.

  • Good... I will do the hiddenfor() to get the ID. However my doubt is still when I send the data to the controller and the check are all null.

  • Worked now?

Show 2 more comments

1 answer

2


It is not good practice to leave in the same Action very different functions, such as assembling a Viewmodel and persist a new user. The correct thing would be to do the following:

public ActionResult UsuarioNovo() 
{
    UsuarioViewModel usuarioViewModel = new UsuarioViewModel {
        ListaFornecedorViewModels = new BuscaDadosFornecedorBo().BuscaRequisicaoFornecedorBo(usuarioViewModel.FornecedorBusca, "")
    };
    ViewData["Colaborador"] = _userLogado;
    return View(usuarioViewModel);
}

[HttpPost]
public ActionResult UsuarioNovo(UsuarioViewModel usuarioViewModel)
{
    if (usuarioViewModel.ListaFornecedorViewModels != null)
    {
        //Gravar Dados
    }

    return View(usuarioViewModel);
}

As I mentioned in comment, this is a classic case of package use Begincollectionitem. There are several questions and answers as to what you can base, but I will leave the paved way for the solution.

Whether the goal is to work with a list of suppliers with a CheckBox, nothing fairer than to define the CheckBox in the Viewmodel, after all, you will not save the supplier. Just pick up whether it was selected or not.

public class FornecedorViewModel
{
    public bool Selecionado { get; set; }
    public Fornecedor Fornecedor { get; set; }
}

Changing the Viewmodel user:

public class UsuarioViewModel
{
    public int Id { get; set; }
    public string CodigoUsuario { get; set; }
    public string NomeUsuario { get; set; }
    public List<FornecedorViewModel> Fornecedores { get; set; }
}

We’ll have to change our method a little bit GET:

public ActionResult UsuarioNovo() 
{
    UsuarioViewModel usuarioViewModel = new UsuarioViewModel {
        Fornecedores = new BuscaDadosFornecedorBo()
                           .BuscaRequisicaoFornecedorBo(usuarioViewModel.FornecedorBusca, "")
                           .Select(f => new FornecedorViewModel { Fornecedor = f })
                           .ToList()
    };

    ViewData["Colaborador"] = _userLogado;
    return View(usuarioViewModel);
}

Your View, so, here’s the deal:

@if (Model.Fornecedores != null) {
    <div class="table-custom">
        <table cellpadding="0" cellspacing="0" border="0" class="dataTable display">
            <thead>
                <tr>
                    <th class="sorting_disabled" rowspan="1" colspan="1" aria-label=" " style="width: 10px;"> </th>
                    <th>Selecionar</th>
                    <th>CNPJ</th>
                    <th>RazaoSocial</th>
                    <th>Municipio</th>                                    
                </tr>
            </thead>

            <tbody>
                @foreach (var form in Model.Fornecedores) {
                    <tr>
                        <td></td>
                        <td>@Html.CheckBoxFor(_ => form.Selecionado)
                        <td>@form.Fornecedor.Codigocnpj</td>
                        <td>@form.Fornecedor.RazaoSocial</td>
                        <td>@form.Fornecedor.Municipio</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
}

Now let’s use the BeginCollectionItem.

@if (Model.Fornecedores != null) {
    <div class="table-custom">
        <table cellpadding="0" cellspacing="0" border="0" class="dataTable display">
            <thead>
                <tr>
                    <th class="sorting_disabled" rowspan="1" colspan="1" aria-label=" " style="width: 10px;"> </th>
                    <th>Selecionar</th>
                    <th>CNPJ</th>
                    <th>RazaoSocial</th>
                    <th>Municipio</th>                                    
                </tr>
            </thead>

            <tbody>
                @foreach (var form in Model.Fornecedores) {
                    @using (Html.BeginCollectionItem("Fornecedores"))
                    {
                        <tr>
                            <td></td>
                            <td>@Html.CheckBoxFor(_ => form.Selecionado)
                            <td>@form.Fornecedor.Codigocnpj</td>
                            <td>@form.Fornecedor.RazaoSocial</td>
                            <td>@form.Fornecedor.Municipio</td>
                        </tr>
                    }
                }
            </tbody>
        </table>
    </div>
}

With this, it is very easy to finish the logic:

if (usuarioViewModel.Fornecedores != null)
{
    foreach (usuarioViewModel.Fornecedores.Where(f => f.Selecionado))
    {
        // Gravar dados
    }
}
  • I made another comment below. What I did wrong?

  • Friend, this is not a forum. You did not comment, but tried to answer the question. Use the edit button of your question to edit. I’ve done it for you now, but next time edit your question. Do not ask an answer.

  • I got it... I just wanted to send the image to demonstrate the error and I couldn’t get it here.

Browser other questions tagged

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