C# DataAnnotations中的FileExtensions属性无法使用asp.net mvc
我试图在asp.net mvc应用程序中只允许excel文件(.xls和.xlsx),但当我尝试上载excel文件(在我的示例“sale.xlsx”中)时,对于ModelState.IsValid,它显示为false。有什么问题吗 下面是代码 型号:C# DataAnnotations中的FileExtensions属性无法使用asp.net mvc,c#,asp.net,asp.net-mvc,data-annotations,C#,Asp.net,Asp.net Mvc,Data Annotations,我试图在asp.net mvc应用程序中只允许excel文件(.xls和.xlsx),但当我尝试上载excel文件(在我的示例“sale.xlsx”中)时,对于ModelState.IsValid,它显示为false。有什么问题吗 下面是代码 型号: public class ReadExcel { [Required(ErrorMessage = "Please select file")] [FileExtensions(Extensions = ".
public class ReadExcel
{
[Required(ErrorMessage = "Please select file")]
[FileExtensions(Extensions = ".xls,.xlsx", ErrorMessage = "Only excel file")]
public HttpPostedFileBase file { get; set; }
}
视图:
显然,在上传excel时,控件应该在if块内移动(if(ModelState.IsValid))。但事实并非如此。请帮助?什么是您的
文件扩展属性
?文件扩展不是我的,它是默认的。由mvc提供,与[Required]一样,我只是在谷歌上搜索并阅读到属性的类型可能需要为string
-您可以试试吗?建议您查看一个与HttpPostedFileBase
(客户端和服务器端验证)@yogihosting Copy一起使用的验证属性
@using (Html.BeginForm("Index", "ReadExcel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.file, new { type = "file" })
<button id="submitButton" type="submit">Submit</button>
@Html.ValidationMessageFor(model => model.file)
}
[HttpPost]
public ActionResult Index(ReadExcel readExcel)
{
if (ModelState.IsValid)
{
//code
}
return View();
}