在表单中我有一个字段应该采用文件名(浏览文件后)和按钮提交。点击提交文件后应加载到服务器。它工作正常。但是,如果我没有选择任何文件(例如字段为空) - 单击导致异常,因为无法加载。
然后,你好,从mvc和网络技术的新手那里问好。
如何防止这种行为?例如,点击sumbit后如何制作一些弹出消息,输入为空?'?
<form asp-action="Upload" asp-controller="Home" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-sm-7">
<label for="file">Xml file</label>
<div data-width="85%" class="input-group">
<label class="input-group-btn">
<span class="btn btn-primary">
<input id="file" name="Files" type="file" accept=".xml" style="display: none;">Browse…
</span>
</label>
<input type="text" class="form-control" readonly>
</div>
</div>
<div class="col-sm-1"></div>
<div class="col-sm-4" style="margin-top:15px;">
<input type="submit" class="btn btn-primary btn-block" value="Upload" />
</div>
</div>
答案 0 :(得分:1)
我会使用javascript和数据注释来解决这个问题,例如(用作方向):
$(input).click(function(event)
{
...
if($(input).files.length == 0){
$(input).addClass("disabled");
event.preventDefault();
}
...
});
还可以在viewmodel中使用DataAnnotations。如果使用[Required]
- 属性,则无法提交没有文件的表单。
查看https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/adding-validation
答案 1 :(得分:0)
我认为接受的答案是懒惰的,并且javascript会四处走动,只要您有超过1个输入字段,就会变得单调乏味。
遵循MVC模式,代表模型 - 视图 - 控制器。
你需要一个Model,它是从视图中收集的数据,然后在控制器内操作,在你的情况下这是一个文件。
所以你的模型应该是这样的:
public class MyModelName {
[Required(ErrorMessage = "Display a custom error message when the field is not filled out, leave this option out for default error message")]
public IFormFile MyFileName { get; set; }
}
为了能够在一个视图中使用MyModelName
(让我们称之为MyView
并且它得到并发布到控制器内的MyView
动作),你必须让视图知道它的。这是通过在View文件的顶部包含@model MyModelName
(区分大小写)来完成的。当View知道模型时,要使用@Model
引用它,这将调出对象。
现在为您的表单而不是手动添加name
和type
等属性到输入字段使用asp帮助程序。
所以而不是:
<input id="file" name="Files" type="file" accept=".xml" style="display: none;">
像这样写:
<input id="file" asp-for="@Model.MyFileName">
查看使用浏览器开发人员工具生成的内容,您将看到自动添加到输入字段的各种属性。
页面上的任意位置为验证消息添加空格(通常在输入字段下方):
<span asp-validation-for="@Model.MyFileName"></span>
此时您可以通过调用ModelState.IsValid
来进行服务器端验证,如下所示:
[HttpPost]
public IActionResult MyView(MyModelName model){
if(ModelState.IsValid)
//proceed to do whatever with the file
return View(model); //return the model with the validation errors
}
因此,服务器端验证意味着在您在浏览器中看到错误消息之前,该站点将不得不往返于后端。
要在不必访问服务器的情况下进行验证,您需要在视图中包含部分验证脚本,它由默认的Microsoft模板提供。在MyView.cshtml
include的底部(您将需要默认的jquery库):
@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
在此阶段,您将进行客户端验证,除非满足所有验证要求,否则不会提交表单。
如果您还想进行验证,则在partial中添加的验证脚本会提供函数valid()
可以像这样使用:
$('form').on('submit', function(e){
//stop the form from being submitted
e.preventDefault();
if($(this).valid()) {
//do stuff if form is valid
}
//do stuff if form is not valid
})
有关模型validation
的更多信息