Transforms string to decimal within an object

Asked

Viewed 103 times

1

I made a Viewmodel, where in the database the CPF field is decimal(11.0) and in the VM I put as String. In my API the CPF is decimal. Well, when I fill out the field and send the form to the API, the value of the CPF comes with 0.0. This is expected because I didn’t parse. Well, when the form is sent by Ubmit, does it send a json object right? So, I can’t handle it. I was told to use Automapper, but I find a lot to do, just parse/convert a field. Here’s my VM(these annotations are required?)

 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 this 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 recording in the bank(here 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);
        }
    }

and this is where I send to the API(I think it should be here the string parse to decimal, but I don’t know how to do)

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 Cpf is still coming with the mask, but in the API it already reaches 0.0. Where I parse it?

  • 4

    Can’t you change the field type? CPF can contain 0 left, information that in a numeric field will be lost.

  • As @Robertodecampos commented... you should not be storing Cpf as a numeric independent of storing with a mask or without. This will only generate more work on subsequent treatments.

  • I know that, but I can’t change the type. It has to be numerical. I have already talked to the person in charge and it should be so, he told me, so I did not want to persuade him anymore. That’s the point with me. Responding to @Robertodecampos, I will always have to use a padleft(11)

  • I’ve never seen the decimal field type '-', @Robertodecampos is absolutely right.

  • I can’t believe they pulled off the stunt decimal for CPF, I’ve seen too much wrong typing, but this was too much.

2 answers

2

Here 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);;
}

Will be removed from the string all non-numeric characters, so there is no error.

1

If you are sending the CPF with the mask, at the time of the conversion it will not identify as a number, and since it is structured this way, remove the mask before sending 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);
    }
  • danspark, if I do it this way the end of it looks like this:123 345 456 and I can’t record it either.

  • Replace apostrophes with apses and characters ' 0' with null

  • danspark, so it worked. But I created Cpf in the bank as decimal and when I write write like this: 12345678922.0 and not 12345678922. That’s another post, right? I’ll mark your reply, but you need to edit and post as per your comment.

Browser other questions tagged

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