c# – Problem sending model to controller

Question:

I have a problem to forward my model to the control:

Class:

    public class Pessoa {
        public virtual long Id {get; set;}
        public virtual string Nome {get; set;}
        public virtual ETipo Tipo {get; set;}

        public virtual List ListaClientes {get; set;}
    }

View:

    @using Projeto.Model.Enum
    @model projeto.Model.Cadastro.Pessoa
    @{
        title = ".."

        List lstCliente = Model.ListaClientes;
    }

    @using (Ajax.BeginForm("SalvaPessoa", "Home", new AjaxOptions { HttpMethod = "POST"})) {

        @Html.Hidden(m => m.Id)
        @Html.Hidden(m => m.Nome)
        @Html.Hidden(m => m.Tipo)

        @foreach(var x in @lstCliente){

            Cliente
            @Html.CheckboxFor(m => m.ListaClientes.IsAtivo, new{ class = "form"})

        }

        Salvar

        

        
    }

Controller:

    public JsonResult SalvaPessoa(Pessoa model){
        ...
    }

So, all fields are arriving just right in my SalvaPessoa() method, except for my list whose IsAtivo bool inside the form was changed;

All fields are valued, even the list already comes from my ActionResult() Valued.

Can someone help me on how to make this list of mine to be sent to SalvaPessoa()?

Answer:

The correct thing would be:

public class Pessoa 
{
    public virtual long Id {get; set;}
    public virtual string Nome {get; set;}
    public virtual ETipo Tipo {get; set;}

    public virtual List<Cliente> ListaClientes {get; set;}
}

Another thing is to assemble the form with BeginCollectionItem :

@using (Ajax.BeginForm("SalvaPessoa", "Home", new AjaxOptions { HttpMethod = "POST"})) {

    @Html.Hidden(m => m.Id)
    @Html.Hidden(m => m.Nome)
    @Html.Hidden(m => m.Tipo)

    @foreach(var x in @lstCliente)
    {
        @Html.Partial("_Cliente", x)
    }

}

_Cliente.cshtml

@model SeuProjeto.Models.Cliente

@using (Html.BeginCollectionItem("ListaClientes"))
{
    Cliente
    @Html.CheckboxFor(m => m.IsAtivo, new { @class = "form"})
}

Once this is done, the bind on the Controller will appear correct.

Scroll to Top