Transforms string into decimal within an object

1

I made a ViewModel, where in the database the CPF field is decimal (11,0) and in the VM I put it as String. In my API the CPF is decimal. Well, when I fill in the field and send the form to the API, the value of the CPF arrives with 0.0. This is expected since I did not parsee. Well, when the form is submitted by submit, it sends a json object right? So I can not handle it. I was told to use AutoMapper, but I think a lot, just to parse / convert a field. Here is my VM (do you need these anotations?)

 public class FuncionarioViewModel
    {
        [Key]
        public int id { get; set; }

        [Required(ErrorMessage = "Nome do funcionário é obrigatório", AllowEmptyStrings = false)]
        [Display(Name = "Nome")]
        public String nome { get; set; }

        [Required(ErrorMessage = "Data de Nascimento do funcionário é obrigatório", AllowEmptyStrings = false)]
        [Display(Name = "Data de Nascimento")]
        [DataType(DataType.Date, ErrorMessage = "formato de data invalido")]
        public DateTime dataNascimento { get; set; }

        //[Required(ErrorMessage = "CPF do funcionário é obrigatório", AllowEmptyStrings = false)]
        [Display(Name = "CPF")]
        [DataType(DataType.Text, ErrorMessage = "Formato inválido")]
        public String cpf { get; set; }

        [Display(Name = "Nome da Cidade")]
        public String NomeCidade { get; set; }

        [Required(ErrorMessage = "Cidade do funcionário é obrigatório", AllowEmptyStrings = false)]
        [Display(Name = "Cidade")]
        public virtual int cidade { get; set; }
    }

My Model is the one in the API

public class Funcionario
    {
        [Key]
        public int id { get; set; }
        [Required]
        public String nome { get; set; }
        [Required]
        public DateTime dataNascimento { get; set; }
        [Required]
        public decimal cpf { get; set; }
        public String NomeCidade { get; set; }
        [Required]
        public int cidade { get; set; }
    }

This method I trigger the Stored Proc that writes to the bank (here is the CPF is already 0.0)

public class PostFuncionario
    {
        BancoContext banco = new BancoContext();

        //Método que insere um novo funionario no banco de dados.
        public HttpResponseMessage PostFuncionarios(Funcionario funcionario)
        {
            banco.Database.ExecuteSqlCommand("exec sp_ins_funcionarios @nome, " +
                                             "@datanascimento, " +
                                             "@cpf, " +
                                             "@cidade", 
                                             new SqlParameter("@nome", funcionario.nome),
                                             new SqlParameter("@datanascimento", funcionario.dataNascimento),
                                             new SqlParameter("@cpf", funcionario.cpf),
                                             new SqlParameter("@cidade", funcionario.cidade));

            return new HttpResponseMessage(HttpStatusCode.OK);
        }
    }

This is where I send to the API (I think it should be the string parse here for decimal, but I do not know how to do it)

public async Task PostFuncionarioVM(FuncionarioViewModel funcionario)
        {
            string url = $"http://localhost:56137/api/PostFuncionario";
            var uri = new Uri(string.Format(url));
            var data = JsonConvert.SerializeObject(funcionario);
            var content = new StringContent(data, Encoding.UTF8, "application/json");
            HttpResponseMessage response = null;
            response = await client.PostAsync(uri, content);
        }

Here the cpf is still coming with the mask, but in the API it already arrives 0.0. Where do I parse it?

    
asked by anonymous 13.08.2018 / 14:11

2 answers

2

Here is a "clean" solution with Regex :

using System.Text.RegularExpressions;

public async Task PostFuncionarioVM(FuncionarioViewModel funcionario)
{
    var uri = new Uri("http://localhost:56137/api/PostFuncionario");

    funcionario.cpf = Regex.Replace(funcionario.cpf, "[^0-9]", string.Empty);

    var data = JsonConvert.SerializeObject(funcionario);
    var content = new StringContent(data, Encoding.UTF8, "application/json");

    HttpResponseMessage response = await client.PostAsync(uri, content);;
}

All non-numeric characters will be removed from string , so there is no error.

    
13.08.2018 / 14:41
1

If you are sending the CPF with the mask, at the time of the conversion it will not identify you as a number, and since it is structured this way, remove the mask before sending it to the API.

    public async Task PostFuncionarioVM(FuncionarioViewModel funcionario)
    {
        string url = $"http://localhost:56137/api/PostFuncionario";
        var uri = new Uri(string.Format(url));

        funcionario.cpf = funcionario.cpf
        .Replace(".", null)
        .Replace("-", null);

        var data = JsonConvert.SerializeObject(funcionario);
        var content = new StringContent(data, Encoding.UTF8, "application/json");
        HttpResponseMessage response = null;
        response = await client.PostAsync(uri, content);
    }
    
13.08.2018 / 14:21