开发者

Asp.Net MVC 3 Action Result parameters and data validation: are all primitive properties to be string?

Validating a form with Data Annotations using MVC.

Are you to define all properties of an input object parameter as string with data annotations so one can check the model state to catch errors, or should I just use the native data types for objects?

I created numerous "control function" models in bound which are identical to the View Models with the exception of Regex validators and "string" for each field.

Doing this seems to be unnecessary complexity. Just want to make sure I am on the right track, or that the double data models is something that MVC normally handles anyway.

For example:

public class Product
{    public int     id          {get;set;}
     public string  name        {get;set;}
     public double? retailPrice {get;set;}
     [Required]
     public int     deptId      {get;set;}
     [Required]
     public bool    acti开发者_StackOverflow中文版ve      {get;set;}
}

public class Product
{    [RegularExpression(@"^\d*$", ErrorMessage = "*")]
     public string  id          {get;set;}
     public string  name        {get;set;}
     [RegularExpression(@"^\d*$", ErrorMessage = "*")]
     public string  retailPrice {get;set;}
     [RegularExpression(@"^\d+$", ErrorMessage = "*")]
     public string  deptId      {get;set;}
     [RegularExpression(@"(?i)^true$|^false$", ErrorMessage = "*")]
     public string  active      {get;set;}
}

Could just use the first as the inbound object, or use the second and convert to the first upon successful validation.


You should define your view models to have properties (or fields) with the correct data type. There is no requirement for them to be strings. If you have defined a property to be of type int and the model binder binds the request data to it, but cannot coerce the value to an int then the property will not be set and the model state will indicate that there is an error.

Some people have the concern of wanting to rerender the page and still have the user value in the textbox to allow them to correct it. If you use the built in Html helper methods, then this will be done for you as it looks to see if there is a model state error for that field and if there is, it will try and find the value from the request data and use that instead.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜