user1613797
user1613797

Reputation: 1267

Validation Attributes in Controller

I write my own attributes to validate models in ASP.NET MVC:

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

and I use such attributes this way:

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

Now, I want to make it work in controller and I added this attribute to a property, instead of model:

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

But my attribute is never executed. How can I make validation work in controller without using a model?

Upvotes: 1

Views: 1506

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

This is not supported. Just write a view model to wrap all the arguments of the action:

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

which might look like this:

public class EmployeePhotoViewModel 
{
    public string Id { get; set; }

    [ValidateImage]
    public HttpPostedFileBase File { get; set; }
}

Upvotes: 2

Related Questions