我正在尝试允许使用引导模式弹出窗口在模式弹出窗口上上传文件。但是它总是为type="file"返回null
我尝试过以下解决方案,但没有成功:在引导模式中使用时,MVC中的文件上传返回null
它总是返回null。如果我直接将其作为单独的页面运行,那么它可以正常工作,但只是弹出窗口有问题。
我试图改变ajax上的内容类型,但后来它给我这个错误"所需的防伪表单字段__requestverificationtoken不存在"
我已经使用开发工具测试了页面发布的内容:在此处输入图像描述
这是我的代码:
控制器:[HttpPost][ValidateAntiForgeryToken]公共异步任务创建([绑定(包括="ID, FileName,链接,SourceType,评论,SourceDate,DateCreated,DateModified,ProjectID")]ProjectSource project ectSource,HttpPostedFileBase上传文件){if(ModelState.IsValid){//上传方法1 var fileSavePath = ""; if(HttpContext.Request.Files.AllKeys()) { // 从Files集合var httpPostedFile=HttpContext.Request.Files[0]获取上传的图像;
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
fileSavePath = (HttpContext.Server.MapPath("~/xyz/") + httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
//upload method 2
if (uploadFile != null && uploadFile.ContentLength > 0)
{
try
{
string path = Path.Combine(Server.MapPath("~/xyz/"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
}
else
{
ViewBag.Message = "You have not specified a file.";
}
db.ProjectSources.Add(projectSource);
await db.SaveChangesAsync();
return " File : " + ViewBag.Message + " == " + fileSavePath;
}
return " File : " + ViewBag.Message +" === "+sb.ToString();
}
视图:
@model CharterPortal. Models.ProjectSource
@{布局="";
@Scripts.Render("~/Scripts/jquery-2.2.3.min.js")
@Scripts.Render("~/Scripts/moment.min.js")
@Scripts.Render("~/Scripts/bootstrap.min.js")
@Scripts.Render("~/Scripts/bootstrap-datetimepicker.min.js")
@Scripts.Render("~/Scripts/bootstrap.fd.js")
}
@using (Html.BeginForm("Create", "ProjectSource", FormMethod.Post, new { enctype = "multipart/form-data" , @id="ajaxForm"}))
{
@Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
@*@Html.ValidationSummary(true, "", new { @class = "text-danger" })*@
<div class="form-group">
@Html.Label("Source file", htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-6">
@Html.EditorFor(model => model.FileName, new { htmlAttributes = new { @class = "form-control" } })
@*<input type="file" name="uploadFile" />*@
@Html.TextBox("uploadFile",null, new { @class = "form-control", type = "file" })
@*<a href="../ProjectSource/FileUpload" id="open_btn" class="btn btn-orange" target="_blank">Add file</a>*@
@Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
</div>
</div>
@*<div class="form-group">
<div class="col-md-10" id="files" style="padding-left:40px;">
</div>
</div>*@
<div class="form-group">
@Html.LabelFor(model => model.Link, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-6">
@Html.EditorFor(model => model.Link, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Link, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.SourceType, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-6">
@Html.EditorFor(model => model.SourceType, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.SourceType, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Comments, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-6" style="color:black;">
@Html.TextAreaFor(model => model.Comments, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Comments, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.SourceDate, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-6" style="color:black;">
@Html.EditorFor(model => model.SourceDate, new { htmlAttributes = new { @class = "form-control datepicker datefield" } })
@Html.ValidationMessageFor(model => model.SourceDate, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-med btn-orange" data-dismiss="modal">Cancel</button>
<input class="btn btn-med btn-orange" type="submit" name="submit" value="Add" />
</div>
}
ajax:$('form', dialog).提交(函数(事件){event.preentDefault();
$.ajax({
url: this.action,
type: this.method,
async: true,
data: $(this).serialize(),
contentType:this.enctype,
success: function (result) {
if (result) {
alert(result)
//Refresh
} else {
alert(result)
}
}
});
return false;
});
我希望得到很好的工作解决方案:提前感谢您的时间。
谢啦
大约一年来,我一直在使用这段代码来解决这个问题和ModelState. IsValid的部分。干杯。
$(function () {
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
$('#modal').on('shown.bs.modal', function () {
$.validator.unobtrusive.parse($(this));
});
$('#modal').on('hidden.bs.modal', function () {
$('#spinner').remove();
});
$.ajaxSetup({ cache: false });
});