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?
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.