remove mask to save to database

Asked

Viewed 3,152 times

1

I am using Maskmoney to create a mask in the field for the user to type. wanted to remove the mask, saving only the numbers and the comma (2 decimal places) in the bank.

R$ 1.300.000,00

saving only

1300000.00

I’m using Asp.net-mvc, follow the controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "PessoaID,Nome,Telefone,Celular,Whatsapp,Email,CPF,Tipo,RG,CTPS,DataNascimento,DataAdmissao,DataDemissao,Senha,CargoID")] Funcionario funcionario)
    {
        //salario = Convert.ToString(salario);
        salario = Regex.Replace(salario, "[^0-9,]", "");

        funcionario.Salario = Convert.ToDecimal(salario);
        funcionario.tipo = 1;
        if (ModelState.IsValid)
        {
            db.Pessoas.Add(funcionario);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.CargoID = new SelectList(db.Cargos, "CargoID", "Descricao", funcionario.CargoID);
        return View(funcionario);
    }

Create:

@model SAQ.Models.Funcionario

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4 onmouseover="tooltip.pop(this, 'Este é meu texto na tooltip.')">Funcionario</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Nome, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Nome, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Telefone, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Telefone, new { htmlAttributes = new { @class = "form-control telefone" } })
            @Html.ValidationMessageFor(model => model.Telefone, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Celular, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Celular, new { htmlAttributes = new { @class = "form-control celular", id = "txt-tel" } })
            @Html.ValidationMessageFor(model => model.Celular, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Whatsapp, htmlAttributes: new { @class = "control-label col-md-2", id = "bt-copiar", title = "Clique em mim para copiar o Celular" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Whatsapp, new { htmlAttributes = new { @class = "form-control celular", id = "txt-wpp", title = "Clique no Texto WhatsApp ao lado para copiar o Celular" } })
            @*<div class="btn" id="bt-copiar">Copiar</div>*@
            @Html.ValidationMessageFor(model => model.Whatsapp, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CPF, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CPF, new { htmlAttributes = new { @class = "form-control cpf" } })
            @Html.ValidationMessageFor(model => model.CPF, "", new { @class = "text-danger" })
        </div>
    </div>

    @*<div class="form-group">
        @Html.LabelFor(model => model.tipo, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.tipo, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.tipo, "", new { @class = "text-danger" })
        </div>
    </div>*@

    <div class="form-group">
        @Html.LabelFor(model => model.RG, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.RG, new { htmlAttributes = new { @class = "form-control rg" } })
            @Html.ValidationMessageFor(model => model.RG, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CTPS, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CTPS, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CTPS, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.DataNascimento, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DataNascimento, new { htmlAttributes = new { @class = "form-control data" } })
            @Html.ValidationMessageFor(model => model.DataNascimento, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.DataAdmissao, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DataAdmissao, new { htmlAttributes = new { @class = "form-control data" } })
            @Html.ValidationMessageFor(model => model.DataAdmissao, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Salario, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Salario, new { htmlAttributes = new { @class = "form-control " } })
            @Html.ValidationMessageFor(model => model.Salario, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Senha, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Senha, new { htmlAttributes = new { @class = "form-control", id="Senha"} })
            @Html.ValidationMessageFor(model => model.Senha, "", new { @class = "text-danger" })
        </div>
    </div>


    <div class="form-group">
        @Html.LabelFor(model => model.CargoID, "Cargo", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("CargoID", null, "Selecione", htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CargoID, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Salvar" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
<script type="text/javascript">
        $(document).ready(function () {
            $(".telefone").inputmask("mask", { "mask": "(99)9999-9999" });
            $(".celular").inputmask("mask", { "mask": "(99)99999-9999" });
            $(".cpf").inputmask("mask", { "mask": "999.999.999-99" }, { reverse: true });
            $(".data").inputmask("mask", { "mask": "99/99/9999" });
            $(".rg").inputmask("mask", { "mask": "99.999.999-9" });
            $(".dinheiro").maskMoney({ prefix: 'R$ ', allowNegative: true, thousands: '.', decimal: ',', affixesStay: true });
        });
</script>
<script> //copia os caracteres do telefone
    $('#bt-copiar').on('click', function () {
        $('#txt-wpp').val($('#txt-tel').val());
    });
</script>
    <script>
        $(document).ready(function (e) {
            $('#Senha').on('focus', function () {
                $(this).attr('type', 'text');
            }).on('blur', function () {
                $(this).attr('type', 'password');
            });
        });
    </script>

}

class (I’m just putting the attribute that gives me trouble):

[DisplayFormat(DataFormatString = "{0:c}")]
[Required(ErrorMessage = "Preencha o Salário")]
[DisplayName("Salário")]
public decimal Salario { get; set; }
  • Use variable = variable. Replace('',", string.Empty);

  • Will you save as a string? Or does your database accept "," as a decimal separator?

  • 1

    @Sorack salary is as decimal in the Bank

  • Your bank accepts decimal with comma?

  • If you want to treat in JS you can use .maskMoney('unmasked') to get the real value. Or in C# you can replace valor = Regex.Replace(valor, @"[^0-9,]", "");

  • @Bacco campo money SQL Server if you put the language in English is one of the examples

  • Usually money removes symbols from the language in this case.

  • The types of data money are not advised. Ideal for storing monetary values is the decimal same. Types of data money present problems in large applications and in database transactions. There is record of data loss and low accuracy in calculations with the type of data money.

  • 2

    Well I do so, set up the Globalization for pt-BR and set up the money fields (money or decimal) $(".dinheiro").maskMoney({ prefix: '', allowNegative: true, thousands: '', decimal: ','}); that way you don’t have to do anything else, but that’s the way I use it.

  • It is correct in terms, but you need to ensure the integrity of your database, in this way, the functions get and set should be used in C# so that the validation of the data does not depend only on the client, because there is no security on the client side. OP has to use Setter and implement C# functions such as var Salario = string.Join("", Salario.Where(char.IsDigit))/100;.

  • 1

    @Virgilionovic his alternative would be something that would work to save the information, but the mask would not be the way the customer wants it...

  • @Fabiosouza I imagined that this is customer stuff, complicated !!! as I said is the way I follow I thought it wasn’t even cool to put an answer... I believe you should do this in the controller, so.

  • @Virgilionovic I tried to do for the controller using Regex.Replace but since the class is set to decimal, it doesn’t even send the data to the controller

  • put an extra field in your controller method more or less like this: public ActionResult Store(string Salario, Funcion ... ) then you work the information and change the class variable responsible for the Salary in decimal

  • 1

    @Virgilionovic worked what I said. I posted the answer to how I solved it. Thank you

Show 10 more comments

2 answers

4


I solved my problem like this:

public ActionResult Create([Bind(Include = "PessoaID,Nome,Telefone,Celular,Whatsapp,Email,CPF,Tipo,RG,CTPS,DataNascimento,DataAdmissao,DataDemissao,Senha,CargoID")] Funcionario funcionario, string salario)
{
        salario = Regex.Replace(salario, "[^0-9,]", "");
        funcionario.Salario = Convert.ToDecimal(salario);
}

ie, includes a salary string, and dealt with Regex.Replace then saved normally.

  • Mark as answer, yo.

  • 1

    I don’t know what you mean

  • It’s that you were able to solve your problem with the code you posted, so in order not to look like an unanswered question, mark your answer as the answer to the post. That’s it.

  • 1

    ah yes, but I can only mark my own response after 2 days... the message you can only accept your own answer in 2 days

2

The types of data decimal are saved in the database with the format, i.e., ########.##, therefore, the string of the example in the format R$ 1.300.000,00 has to be passed to the database with the format 1300000.00.

As already said you could use Javascript for this, but there is no security guarantee there.

Using C# you could easily implement a method to replace all non-numeric characters from string and finally convert it into decimal:

public decimal Salario
{
    get { return _salario; }
    set { _salario = value.Replace("R$ ", string.Empty).Replace(".", string.Empty).Replace(",", "."); }
}

This is just one example. You could use several functions to treat the string.

Microsoft recommends the use of .tryParse().

You could still use

var _salario = string.Join("", _salario.Where(char.IsDigit));

_salario = _salario/100;

The above example joins everything numerical character into a single string, so you have to divide by 100, since R$ 1.300.000,00 would return 130000000.

  • Thanks @Stillbuggin but I ended up solving otherwise. I will post here as I solved. Thanks

Browser other questions tagged

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