Question

My model class:

public class Person
{
    [DataType(DataType.Currency)]
    public decimal Salary { get; set; }  
}

My controller

public class PersonController : Controller
{
    public ActionResult Create()
    {
        var person = new Person();
        person.Salary = 100; // setting default value
        return View(person);
    }
    public ActionResult Create(Person person)
    {
        // Save, validate, etc...
    }    
}

My Create view:

@model Person
<h2>Create person</h2>
@using (Html.BeginForm()) {

     <div class="editor-label">
        @Html.LabelFor(model => model.Salary)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Salary)
        @Html.ValidationMessageFor(model => model.Salary)
    </div>  
}     

On clicking SUBMIT, the page shows the following incorrect validation error:

enter image description here

Please, mind the the separator character between the integer and the decimals. I believe the false validation failure roots from the culture info difference. On the server C# uses comma as separator and on the client JS expects a dot. What would be a safe way to fix this issue?

Était-ce utile?

La solution 2

I found no programmatic answer to control server side number=>string conversion in the EditorFor() context. However, the regional settings of the server machine is the decision point which determines the decimal separator. So we just make sure that the regional settings of the server is set properly.

Autres conseils

This StackOverflow question might also be the solution you're looking for:

How should I use EditorFor() in MVC for a currency/money type?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top