Question

I could've sworn this should've been answered a million times before, but I've come up empty after searching for quite a while.

I have a view that is bound to an object. This object should have an image attached to it somehow (I don't have any preferred method). I want to validate the image file. I've seen ways to do this with attributes, for example:

public class ValidateFileAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        var file = value as HttpPostedFileBase;
        if (file == null)
        {
            return false;
        }

        if (file.ContentLength > 1 * 1024 * 1024)
        {
            return false;
        }

        try
        {
            using (var img = Image.FromStream(file.InputStream))
            {
                return img.RawFormat.Equals(ImageFormat.Png);
            }
        }
        catch { }
        return false;
    }
}

However, that requires the type of HttpPostedFileBase on the property in the model:

public class MyViewModel
{
    [ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")]
    public HttpPostedFileBase File { get; set; }
}

That's all well and good, but I can't really use this type in a EF Code First model class, as it's not really suitable for database storage.

So what's the best approach for this?

Was it helpful?

Solution 2

When I got a little further with development of the site, it was inevitable that I started using ViewModels. Creating a model for each view is definately the way to go.

OTHER TIPS

Turned out it was a quite simple solution.

public class MyViewModel
{
    [NotMapped, ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")]
    public HttpPostedFileBase File { get; set; }
}

I set the NotMapped attribute tag to prevent it from being saved in the database. Then in my controller, I get the HttpPostedFileBase in my object model:

    public ActionResult Create(Product product)
    {
        if (!ModelState.IsValid)
        {
            return View(product);
        }
        // Save the file on filesystem and set the filepath in the object to be saved in the DB.
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top