【发布时间】:2019-06-27 04:34:38
【问题描述】:
我有一个模型类:
public class Register
{
public Employee Employee { get; set; }
public Business Business { get; set; }
}
我有一个 HTML 表单,其输入类型文本包含来自 Model 的员工和业务数据以及一个用于加载图像的输入类型文件:
@using (Html.BeginForm(null, null, FormMethod.Post, new { @id = "frmRegister", @enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="div-file">
<input id="inputFile" title="Upload a business image" type="file" name="UploadedFile" accept="image/*" />
</div>
<div class="div-input">
@Html.Label("Name:", htmlAttributes: new { @for = "txtName" })
@Html.EditorFor(model => model.Employee.Name, new { htmlAttributes = new { @class = "form-control", @id = "txtName" } })
</div>
<div class="div-input">
@Html.Label("Age:", htmlAttributes: new { @for = "txtAge" })
@Html.EditorFor(model => model.Employee.Age, new { htmlAttributes = new { @class = "form-control", @id = "txtAge" } })
</div>
<div class="div-input">
@Html.Label("Company:", htmlAttributes: new { @for = "txtCompany" })
@Html.EditorFor(model => model.Business.Name, new { htmlAttributes = new { @class = "form-control", @id = "txtName" } })
</div>
<div class="div-input">
@Html.Label("Phone:", htmlAttributes: new { @for = "txtPhone" })
@Html.EditorFor(model => model.Business.Phone, new { htmlAttributes = new { @class = "form-control", @id = "txtPhone" } })
</div>
<div class="text-center">
<input type="button" id="btnRegister" value="Register" class="btn btn-default" />
</div>
}
我使用 JQuery 从输入中获取信息并使用 AJAX 传递给控制器:
@section Scripts {
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#btnRegister").on('click', function (e) {
e.preventDefault();
var image = document.getElementById("inputFile").files[0];
var frmRegister = $("#frmRegister").serialize();
$.ajax({
url: '@Url.Action("Create", "Register")',
type: 'POST',
traditional: true,
data: frmRegister,
dataType: 'json',
ContentType: "application/json;utf-8",
cache: false,
success: function (response) {
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
}
控制器:
public ActionResult Create(FormCollection collection)
{
//HttpPostedFileBase file = Request.Files["UploadedFile"];
return View();
}
问题是:图片文件也怎么传?
【问题讨论】:
-
This 可能会对您有所帮助。
-
不行,HttpPostedFileBase 文件 = Request.Files["UploadedFile"];为空。
标签: c# jquery ajax asp.net-mvc-4