开发者

asp.net MVC 2 Validating File uploads with data annotation

开发者 https://www.devze.com 2022-12-22 14:02 出处:网络
I\'m trying to validate a form using Data Annotation. It seems great for string types and integers, but for a file upload, I couldn\'t validate from the class. It would just be sent a string \"HttpPos

I'm trying to validate a form using Data Annotation. It seems great for string types and integers, but for a file upload, I couldn't validate from the class. It would just be sent a string "HttpPos开发者_C百科tedFileWrapper". Does anyone have any tips?

Thanks


You can just use data annotations as per general usage.

For example, a viewmodel such as:

public class UpdateSomethingViewModel {
    [DisplayName("evidence")]
    [Required(ErrorMessage="You must provide evidence")]
    [RegularExpression(@"^abc123.jpg$", ErrorMessage="Stuff and nonsense")]
    public HttpPostedFileWrapper Evidence { get; set; }
}

Then in your controller just the usual:

[HttpPost]
public ActionResult UpdateSomething(UpdateHSomethingViewModel model)
{
    if (ModelState.IsValid)
    {
        // do stuff - plenty of stuff
        // weee, we're off to see the wizard.

        return RedirectToAction("UpdateSomethingSuccess", model);
    }

    return View(model);
}

I've just tested (albeit in MVC2/.net 4) and it worked a treat.

Hope that helps.

Cheers, Terry

0

精彩评论

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

关注公众号