I am working in MVC2 .net and getting problem on file upload. If file size exceeds form the limit then i want to show some exception on the same page.
+2
A:
In the past I have created an Image Size Attribute and used data annotations to validate images.
public sealed class ImageSizeAttribute : ValidationAttribute
{
public int Width { get; set; }
public int Height { get; set; }
private const string DefaultErrorMessage = "{0} dimensions cannot be greater than {1} x {2}";
public ImageSizeAttribute(int width, int height)
: base(DefaultErrorMessage)
{
Width = width;
Height = height;
}
public override string FormatErrorMessage(string name)
{
return string.Format(CultureInfo.CurrentUICulture, ErrorMessageString, name, Width, Height);
}
public override bool IsValid(object value)
{
// Turn HttpPostedFileBase into Image and validate size...
}
}
In your view model you can now just add an attribute to validate it.
[ImageSize(200, 200)]
public HttpPostedFileBase Avatar { get; set; }
In your view make sure you at least have a validation message
<%= Html.ValidationMessageFor(u => u.Avatar) %>
and you can read this post about enabling client validation
Now in your controller you can do your validation and if something goes wrong just return the same view with the existing model and you will see the error messages.
if (ModelState.IsValid)
{
// More validation and saving.
...
return RedirectToRoute("UserDetails", ...);
}
return View(model);
Steve Hook
2010-08-02 12:25:17