2010-08-02 34 views
0

我正在使用MVC2 .net並且在文件上傳時遇到問題。如果文件大小超過限制,那麼我想在同一頁面上顯示一些例外。重定向到mvc .net中應用程序錯誤的相同頁面

+0

嗨,也許這篇文章可以幫助http://stackoverflow.com/questions/3007737/how-can-i-handle-maxrequestlength-exceptions-elegantly – uvita 2010-08-02 12:24:50

回答

2

在過去,我創建了一個圖像大小屬性並使用數據註釋來驗證圖像。

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

在您的視圖模型中,您現在可以添加一個屬性來驗證它。

[ImageSize(200, 200)] 
public HttpPostedFileBase Avatar { get; set; } 

在你看來要確保你至少有一個驗證消息

<%= Html.ValidationMessageFor(u => u.Avatar) %> 

,你可以看到這篇文章關於enabling client validation

現在在你的控制器,你可以做你驗證,如果發生錯誤只是返回與現有模型相同的視圖,您將看到錯誤消息。

if (ModelState.IsValid) 
{ 
    // More validation and saving. 
    ... 
    return RedirectToRoute("UserDetails", ...); 
} 
return View(model); 
相關問題