<script type="text/javascript">
$.validator.addMethod('accept', function () { return true; });
</script>
@using (Html.BeginForm("Create","My controller",FormMethod.Post,new {enctype = "multipart/form-data"})) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-field">
<input type="file" id="File" name="File" accept="image/*" />
</div>
我无法在打开 JS 的情况下上传文件(当我单击提交时,文件输入周围会出现一个黄色框,之后什么也没有发生)。
当我关闭 JS 时,我的表单会提交。
通过上面的 3 行,文件上传表单神奇地与 JS 配合使用。我在我的一个项目中找到了这些,但我不记得它们的作用或为什么需要它们。
你能给我解释一下吗?
编辑
View 的完整代码。
@using EDoctor.Properties
@using EDoctor.Resources
@model EDoctor.Models.DoctorProfileViewModel
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$.validator.addMethod('accept', function () { return true; });
</script>
@using (Html.BeginForm("Create","DoctorProfiles",FormMethod.Post,new {enctype = "multipart/form-data"})) {
@Html.ValidationSummary(true)
<fieldset>
<legend>DoctorProfiles</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Model.PhotoFileUrl)
</div>
<div class="editor-field">
<input type="file" id="File" name="File" accept="image/*" />
@Html.ValidationMessage("UploadFile")
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Model.LicenseNumber)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Model.LicenseNumber)
@Html.ValidationMessageFor(model => model.Model.LicenseNumber)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Model.FirstName)
@Html.ValidationMessageFor(model => model.Model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Model.LastName)
@Html.ValidationMessageFor(model => model.Model.LastName)
</div>
@Html.HiddenFor(model => model.Model.UserId)
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
最佳答案
您已关闭对文件类型的验证。默认情况下,html 文件类型具有接受 特定类型文件的属性。 Accept
字段控制允许的文件类型。
$.validator.addMethod('accept', function () { return true; });
通过添加始终返回 true(成功
)的验证方法。结果是任何文件类型
关于javascript - 客户端文件大小结束格式验证。为什么 JS 会阻止文件上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15490472/