【问题标题】:Validation Attributes in Controller控制器中的验证属性
【发布时间】:2013-05-28 07:23:19
【问题描述】:

我编写自己的属性来验证 ASP.NET MVC 中的模型:

public class ValidateImage : RequiredAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        // validate object
    }
}

我就是这样使用这些属性的:

public class MyModel
{
    [ValidateImage]
    public HttpPostedFileBase file { get; set; }
}

现在,我想让它在控制器中工作,我将此属性添加到属性中,而不是模型:

public ActionResult EmployeePhoto(string id, [ValidateImage] HttpPostedFileBase file)
{
    if(ModelState.IsValid)
    {
    }
}

但是我的属性永远不会被执行。如何在不使用模型的情况下在控制器中进行验证?

【问题讨论】:

    标签: c# asp.net-mvc custom-attributes


    【解决方案1】:

    不支持。只需编写一个视图模型来包装动作的所有参数:

    public ActionResult EmployeePhoto(EmployeePhotoViewModel model)
    {
        if (ModelState.IsValid)
        {
        }
    }
    

    可能看起来像这样:

    public class EmployeePhotoViewModel 
    {
        public string Id { get; set; }
    
        [ValidateImage]
        public HttpPostedFileBase File { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 2015-10-08
      • 2014-05-31
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多