开发者

Redirect to the same page on application error in mvc .net

开发者 https://www.devze.com 2023-01-09 16:24 出处:网络
I am working in MVC2 .net and getting pr开发者_运维技巧oblem on file upload. If file size exceeds form the limit then i want to show some exception on the same page.In the past I have created an Image

I am working in MVC2 .net and getting pr开发者_运维技巧oblem on file upload. If file size exceeds form the limit then i want to show some exception on the same page.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消