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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With