I am using Data Annotations to validate my Model in ASP.NET MVC. This works well for action methods that has complex parameters e.g,
public class Params
{
[Required] string Param1 {get; set;}
[StringLength(50)] string Param2 {get; set;}
}
ActionResult MyAction(Params params)
{
If(ModeState.IsValid)
{
// Do Something
}
}
What if I want to pass a single string to an Action Method (like below). Is there a way to use Data Annotations or will I have to wrap the string into a class?
ActionResult MyAction(string param1, string param2)
{
If(ModeState.IsValid)
{
// Do Something
}
}
DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.
In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.
Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.
ValidationAttribute, has an important property, ErrorMessage. This property get or set the custom validation message in case of error.
Create your own model...
public class Params
{
[Required] string param1 {get; set;}
[StringLength(50)] string param2 {get; set;}
}
And change your signature of your server side controller:
[HttpGet]
ActionResult MyAction([FromUri] Params params)
{
If(ModeState.IsValid)
{
// Do Something
}
}
If your client side code already worked you don't have to change it... Please, note that the properties of your Model are the same of the parameter you are passing now (string param1, string param2
)... and they are case sensitive...
EDIT: I mean that you can call your controller in this way:
http://localhost/api/values/?param1=xxxx¶m2=yyyy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With