开发者

asp.net mvc - DTO not picking up incorrect input

I have a basic DTO object which I am trying to update, I noticed if I post some data from the UI to the controller and I enter string inside a decimal field the data annotations validation does not pick this up, in fact the string is converted into 0 for some reason...

How do I get my decimal values to remain decimal i.e. throw an error if a string is added, do I need to create a custom value provide开发者_C百科r for this DTO object?

My DTO:

public class FeesDTO
    {
        public int ID{ get; set; }
        //[DataType( DataType.Currency)]
        //[DisplayFormat(ApplyFormatInEditMode=true)]  
        public decimal ClientFee { get; set; }
        public string VAT { get; set; }
        public string GrossProfit { get; set; }
    }

If I want to update my fees and I enter 'something' inside the ClientFee field this turns the string input into 0...

NOTE:

The commented out data annotations did not work... Is this the correct way to do this?


when you enter a string value e.g "xyz" for ClientFee which is a decimal variable, it can not be converted to decimal and you will get 0 as value of clientfee but when form is rendered again you will see validation message telling you that

xyz is not valid for field clientfee

this is perhaps due to the fact that when modelbinder fail to convert xyz to decimal it adds the error in Modelstate dictionary's error collection. you can make this value string in your viewmodel and validate it yourself using regex and when you are to store it to db you can convert it to your entity with AutoMapper to similar utility.


I think you need to be using the Data Annotation validators:

http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs

Implement one on the Decimal field that throws a validation error if the Control is posted to with a non decimal entry.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜