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

有些话、适合烂在心里 提交于 2019-11-28 07:27:43

问题


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.


回答1:


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
}


来源:https://stackoverflow.com/questions/14718425/cant-get-mvc-4-fileextensions-attribute-to-work-on-viewmodel-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!