Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
971 views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...