Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Data Annotations to validate parameters passed to an Action method of a Controller?

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  
   }  
}  
like image 834
dannie.f Avatar asked Apr 26 '10 22:04

dannie.f


People also ask

How do you validate data annotations?

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.

Can we do validation in MVC using data annotations?

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.

How do you use data annotations?

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.

Which property of required data annotation is used to set the error message on validation?

ValidationAttribute, has an important property, ErrorMessage. This property get or set the custom validation message in case of error.


1 Answers

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&param2=yyyy

like image 132
Ciccio Avatar answered Oct 20 '22 15:10

Ciccio