无法获得MVC 4 FileExtensions属性视图模型上工作的财产 [英] Can't get MVC 4 FileExtensions Attribute to work on ViewModel property

查看:158
本文介绍了无法获得MVC 4 FileExtensions属性视图模型上工作的财产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要上传一个CSV文件,我想限制它扩展为.csv

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

所以我增加了后续物业我的ViewModel:

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)

但是只要它打我的ModelState.IsValid检查返回我的错误信息无效必须选择.csv文件。

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.

推荐答案

问题是,FileExtensionsAttribute仅适用于字符串变量。检查HttpPostedFileBase的文件扩展名最简单的方法变量是使用这个简单的属性。它解决了我的问题。

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
}

这篇关于无法获得MVC 4 FileExtensions属性视图模型上工作的财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆