简体   繁体   中英

ASP.NET MVC3 can't bind a decimal field from a TextBoxFor to my Model

This is probably a dummy question, but I'm stuck with a problem I can't resolve by myself.

I'm working on an ASP.NET MVC3 project. For some reason, on a particular Create page, a decimal field is not binded on the model when the page is validated and I can't understand why.
Here is my code :

@model ModelA

/*some TextBoxFor or others DropDownListFor, all of them working well*/

@Html.TextBoxFor(m => m.ModelB.ModelC.MyField, new { @id = "txtMyField" })

When I validate the page, the model ModelA is correctly filled EXCEPT for this particular field MyField . Others fields are OK, for exemple :

@Html.TextBoxFor(m => m.ModelB.AnotherField, new { @id = "txtAnotherField" })

perfecly works, and others properties of ModelB are correctly filled.

My models

ModelA contains a property of type ModelB called ModelB .
ModelB contains a property of type ModelC called ModelC .
ModelC contains a property called MyField . (I'll probably add one or two more in the future). This field is a decimal field, without any DataAnnotation or anything.

public decimal MyField { get; set; }


By the way, when in my browser's console I request

$('#txtMyField').val()

it displays the good value, for example 12.54 .


What I tried

  • Change this decimal field to a float type, the problem is the same.
  • Put it in an EditorFor instead of a TextBoxFor, the problem is the same.
  • Put the field MyField in ModelB. The only ModelB's property to 0 is MyField.


Why is this field a rebel ? I probably do something wrong, but I can't understand where... Can someone explain me where is my mistake ?
Thank you !

Ok, so here is the solution :

A "correct" decimal value looks like 45.68 with a . as a separator.
But the application is a non-English application, and the separator need to be a , . By default, 45,68 is not a correct number. So I added this piece of code :

jQuery.extend(jQuery.validator.methods, {
    number: function (value, element) {
        return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);
    }
});

and 45,68 is recognized as a correct number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM