是否有可能使用数据注释验证传递给控制器​​的操作方法参数? [英] Is it possible to use Data Annotations to validate parameters passed to an Action method of a Controller?

查看:118
本文介绍了是否有可能使用数据注释验证传递给控制器​​的操作方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的数据注释来验证我的ASP.NET MVC模型。这非常适用于行动的方法有复杂的参数例如,

 公共类PARAMS
{
    [必填]字符串参数1 {搞定;组;}
    [StringLength(50)]字符串参数2 {搞定;组;}
}
的ActionResult MyAction(PARAMS PARAMS)
{
   如果(ModeState.IsValid)
   {
      // 做一点事
   }
}

如果我想通过一个字符串的操作方法(如下图所示)什么。有没有办法使用数据注释的方式或将我的字符串包装成一个类?

 的ActionResult MyAction(字符串参数1,字符串参数2)
{
   如果(ModeState.IsValid)
   {
     // 做一点事
   }
}


解决方案

我不相信有一个数据注释方法你提出了什么。但是,如果你想在调用操作方法之前发生的验证,可以考虑添加自定义模型绑定属性的参数,并指定要使用一个特定的模型粘合剂。

例如:

 公众的ActionResult MyAction [ModelBinder的(typeof运算(StringBinder)字符串参数1,[ModelBinder的(typeof运算(StringBinder2)字符串参数2)
{
  .........
}

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  
   }  
}  

解决方案

I don't believe there is a Data Annotations method to what you are proposing. However, if you want your validation to happen before the action method is invoked, consider adding a custom model binder attribute to the parameter and specify a specific model binder you want to use.

Example:

public ActionResult MyAction [ModelBinder(typeof(StringBinder)] string param1, [ModelBinder(typeof(StringBinder2)] string param2)
{
  .........
}

这篇关于是否有可能使用数据注释验证传递给控制器​​的操作方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆