我有一个AspNet Core网络应用程序,其中包含一个简单的视图,允许用户上传文件。 视图模型中的file属性具有[Required]属性。但是,即使没有选择文件,单击提交按钮也会执行发布。
查看型号:
public class DocumentUploadViewModel
{
[HiddenInput]
public string Id { get; set; }
[Required]
[FileExtensions(Extensions = "pdf")]
public IFormFile Document { get; set; }
}
查看:
@using App.Models.DocumentViewModels
@model DocumentUploadViewModel
@{
ViewData["Title"] = "Upload Document";
}
<h2>Upload Document</h2>
<form method="post" enctype="multipart/form-data" asp-controller="Document" asp-action="Upload" >
<div class="form-horizontal">
<div class="form-group">
<input asp-for="Id" />
<label class="col-md-2 control-label">Document</label>
<div class="col-md-10">
<input class="form-control" type="file" asp-for="Document" />
<span asp-validation-for="Document" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input id="save" name="save" type="submit" value="Upload" class="btn btn-default pull-right" />
</div>
</div>
</div>
</form>
答案 0 :(得分:2)
您必须拥有适当的JavaScript脚本引用视图,以便客户端验证能够正常工作:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.0.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>