Complex type Bind with AngularJS

5

I'm studying AngularJS and Asp.net MVC and I was not able to bind a Person's CPF property when I perform a POST:

Person Class:

public class Pessoa
{
   protected PessoaFisica() { }

   public Int32 PessoaFisicaID{ get; set; }
   public String Nome { get; set; }
   public Cpf CPF { get; set; } 
   ...

}

CPF Class:

public partial class Cpf
{
        protected Cpf() { }        
        public Int64 Numero { get; private set; }
        ...
}

Controller AngularJS:

...
vm.salvar = function () {

            var pessoaFisica = new Object();
            pessoaFisica.PessoaFisicaID = vm.PessoaFisicaID;
            pessoaFisica.Nome = vm.Nome;

            //Bind do CPF com problema :-(

            //Tentativa 1:
            //pessoaFisica.CPF = new Object();
            //pessoaFisica.CPF.Numero = vm.CPF; 

            //Tentativa 2:
            pessoaFisica.CPF = vm.CPF;

            //Uso o $http.post()
            ajaxService
                    .ajaxPost(
                        pessoaFisica,
                        '/Home/Criar',
                        this.salvarPessoaFisicaOnSuccess,
                        this.salvarPessoaFisicaOnError
                    );   
        }
        ...

MyScreen:

OnthefirsttryIusedthecodebelow,butitdidnotwork:

//Tentativa1:pessoaFisica.CPF=newObject();pessoaFisica.CPF.Numero=vm.CPF;

Error:System.MissingMethodException:Noparameterlessconstructorwasdefinedforthisobject.

OnthesecondattemptIusedthecodebelowanditdidnotwork:

//Tentativa2:pessoaFisica.CPF=vm.CPF;

GetnullinAsp.netMVCcontroller:

What could I be adjusting to get the CPF bind informed?

    
asked by anonymous 22.12.2015 / 02:10

2 answers

1

You need to adjust your ViewModel to receive the same structure that is coming from your post request.

public class PessoaViewModel
{
    public int PessoaFisicaID { get; set; }
    public string Nome { get; set; }
    public CPF cpf { get; set; }
}
public class CPFViewModel
{
    public string Numero { get; set; }
}

See if it solves, and a return.

    
23.12.2015 / 14:15
4

You can solve this problem by creating the Object in this way:

var pessoaFisica = {
    id: 1,
    Nome: 'Renan',
    Cpf: {
        Numero: '232432'
    }
};

But in this way you are not using AngularJS itself, but creating a normal object in javascript .

Using Angular, your object would look something like this:

$scope.person = {
  'id': '1',
  'nome': 'Renan',
  'Cpf': {
     'Numero': '1234678'
  },
}

And in this way you pass $scope.person as an object.

$http.post("Pessoa/Criar/", { person : $scope.person});

On this site you have some examples of like using Angular.

In this Question you have some answers on how to use Angular for this purpose.

    
22.12.2015 / 13:51