8

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.

jalewis
  • 103
  • 1
  • 1
  • 8
  • How can you upload a file using a Textbox in your View ? Because i never tried it like that. I've used ` – Karthik Chintala Feb 06 '13 at 04:22
  • @Karthik Fair question. When it generates the html you get ` – jalewis Feb 06 '13 at 16:58
  • What's this `FileExtensions` attribute? Where is it coming from? That's not something that's built-in ASP.NET MVC. – Darin Dimitrov Feb 06 '13 at 17:10
  • @DarinDimitrov It's a new attribute in .net 4.5 [msdn](http://msdn.microsoft.com/en-us/library/hh192365.aspx) and it seems it is not working with MVC: http://stackoverflow.com/questions/8536589/asp-net-mvc-3-dataannotations-fileextensionsattribute-not-working – nemesv Feb 06 '13 at 17:11
  • 1
    @nemesv, good point. I didn't know about that attribute. Voting to close as duplicate. – Darin Dimitrov Feb 06 '13 at 17:13
  • @DarinDimitrov I saw that question, but wasn't sure it was exactly the same problem. I was originally driven to this version based on another question that used MVC Futures in MVC 3.0 to do the same thing. So that is why I made the assumption that it was supported in .net 4.5 MVC 4.0 – jalewis Feb 06 '13 at 18:21

1 Answers1

3

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
}
Community
  • 1
  • 1