C # MVC How to use currency format

4

I need to use the currency format

When using the annotation:

(Model)

[DataType(DataType.Currency)]

[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]

public Nullable<float> monto { get; set; }

(View)

@Html.EditorFor(model => model.monto_observado, new { htmlAttributes = new { @class = "form-control" } })

It correctly shows the data to be edited:

$26,281,000.00

but when you try to "Save" you validate me

  

The field Monto Observed must be a number.

What do I have to do to be able to use currency format?

    
asked by Rodolfo Mendez Chico 15.01.2018 в 18:01
source

2 answers

3

It is because when converting it to currency format the data type is no longer a float , it is a string . You have to remove everything that is not a number so you can take it when you assign it to your model.

Function in js to unmask money type formats:

function unmaskDinero(dinero) {
    return Number(dinero.replace(/[^0-9\.]+/g, ""));
}

And you assign it with unmaskDinero

model.monto_observado = unmaskDinero(monto$);
    
answered by 15.01.2018 / 18:09
source
2

My Solution

(Model)

[DataType(DataType.Currency)]

[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]

public Nullable<double> monto { get; set; } 

(View)

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "enviar" }))
{
    
    <div class="form-group">
        @Html.LabelFor(model => model.monto_observado, htmlAttributes: new { @class = "control-label col-md-2"})
        <div class="col-md-10">
            @Html.EditorFor(model => model.monto_observado,  new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.monto, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-2 col-md-offset-2">
            <input type="button" id="guardar" value="Guardar" class="btn btn-default"/>
        </div>
        <div class="col-md-3">
            @Html.ActionLink("Regresar", "Index", null, new { @class = "btn btn-default" })
        </div>
    </div>
}

(script)

<script type="text/javascript" language="javascript">

    $(function () {
        $("#guardar").click(function () {            
            
            //igual se pueden validar mas controles

            currency = $("#monto_observado").val();
            $("#monto_observado").val(unmaskDinero(currency));
            
            $("#enviar").submit();
        });
    });

    function unmaskDinero(dinero) {
        return Number(dinero.replace(/[^0-9\.]+/g, ""));
    }

</script>

(Conclutions)

the model shows the numbers as DisplayFormat indicates both the list and the edit after editing, by clicking on the submit button, it is formatted as a decimal number and sends the controller to save the data.

I thank Pikoh, as well as Aaron Romero, his valuable help.

    
answered by 16.01.2018 в 20:23