Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get MVC 4 FileExtensions Attribute to work on ViewModel property

I need to upload a csv file and I want to restrict it's extension to .csv

So I added the follow property to my ViewModel:

[FileExtensions(ErrorMessage = "Must choose .csv file.",Extensions = "csv,txt")]
public HttpPostedFileBase File { get; set; }

In my view I have the following:

@Html.TextBoxFor(m => m.File, new { type = "file"})
@Html.ValidationMessageFor(m => m.File)

However as soon as it hits my "ModelState.IsValid" check it returns invalid with my error message of "Must choose .csv file."

I assume I'm just missing a parameter, but I haven't found a sample of this in use any where yet.

like image 427
jalewis Avatar asked Feb 05 '13 22:02

jalewis


1 Answers

The Problem is that the FileExtensionsAttribute works only on string variables. The easiest way to check the file extension of HttpPostedFileBase variable is to use this simple attribute. It solved my problem.

The only downside is that this new attribute is only validated on serverside so don't forget to check the model state with:

if (ModelState.IsValid)
{
  // Do the work
}
like image 59
Johannes Krackowizer Avatar answered Oct 31 '22 07:10

Johannes Krackowizer