c# - 我有一个带有 httppostedfile 的表单,我想通过 jquery 提交。httppostedfile 提交值为空
问题描述
这是我的 html 代码,其中我有一个表单从用户那里获取一些输入,并且用户上传了一个文件:
<div class="modal fade" id="CreateCompanyModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Create Company</h2>
</div>
<div class="modal-body">
<form id="CreateCompanyForm">
<label>New Company Name</label>
@Html.TextBoxFor(m => m.CreateCompany.Name, new { @class = "form-control" })
<label>Choose File:</label>
<input type="file" id="userFile" name="userFile" /><br />
</form>
</div>
<div class="modal-footer">
<div class="btn-group">
<a href="#" id="btnSaveToCreateCompany" class="btn btn-primary">Confirm</a>
</div>
</div>
</div>
</div>
我在其中序列化表单并将其发送到控制器的 jquery 代码:
$("#btnSaveToCreateCompany").click(function () {
var MyCreateCompanyForm = $("#CreateCompanyForm").serialize();
$.ajax({
type: "POST",
url: "/Company/CreateNewcompany1",
data: MyCreateCompanyForm,
success: function (res) {
console.log(res);
}
})
});
我的控制器功能,我在其中接收表单并实现其背后的逻辑:
[HttpPost]
public ActionResult CreateNewCompany1(HttpPostedFileBase postedFile, ListCreateEditDeleteCompaniesViewModel viewModel)
{
if (ModelState.IsValid)
{
string filePath = "";
filePath = Server.MapPath("~/Images/");
if (postedFile == null)
postedFile = Request.Files["userFile"];
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
filePath = filePath + Path.GetFileName(postedFile.FileName);
if (!System.IO.File.Exists(filePath))
{
postedFile.SaveAs(filePath);
}
else
return RedirectToAction("FileExistsView", "Folder");
string extention = Path.GetExtension(filePath);
if (extention != ".png")
return Json("extention is not png", JsonRequestBehavior.AllowGet);
return Json(true, JsonRequestBehavior.AllowGet);
}
else
return Json("invalid model", JsonRequestBehavior.AllowGet);
}
解决方案
推荐阅读
- amazon-web-services - 我可以暂停/冻结 AWS EC2 专用主机以降低成本吗?
- php - 将 MySQL 字段字符集从 latin1 更改为 utf8_general_ci 打破变音符号 (ä,ö,ü)
- angular - Karma-Jasmine:TypeError:无法读取未定义的属性(读取“get”)
- swift - 将 CVPixelBuffer 转换为 UIImage 的内存泄漏
- android-studio - Android模拟器发白显示问题
- xamarin.forms - 如何从后台安排在 Xamarin ios 中启动应用程序或任务?
- javascript - 一旦生成雷达图,它就会在图例和图表之间留下巨大的空间
- java - 使用没有值的 Java 8 Streams 遍历 java 中的列表
- python - 创建一个函数以在 python 中执行 T-Test
- highcharts - 以角度更改数据序列类型时出现 HighCharts 风刺的问题