【发布时间】:2016-01-09 17:07:09
【问题描述】:
在这种情况下,我如何将<input type="file" id="uploadStudent" /> 上传的文件发布到 mvc 控制器?
Javascript
$.ajax({
url: "/Home/CompleteAttendeeType",
contentType: "application/json;charset=utf-8",
dataType: "JSON",
type: "POST",
data: JSON.stringify({
//PostedFile: "I AM CONFUSED HOW TO UPLOAD?",
AttendeeType: 1,
LicenseNumber: $("#txtLicenseNumber").val(),
LicenseState: $("#txtLicenseState").val(),
SchoolName: $("#txtSchoolName").val(),
SchoolLocation: $("#txtSchoolLocation").val()
})
})
MVC
[HttpPost]
public JsonResult CompleteAttendeeType(CompleteAttendeeTypeRequest request)
{
return Json(string.Empty, JsonRequestBehavior.AllowGet);
}
public enum AttendeeType
{
Professional,
Student,
Owner,
Guest
}
public class CompleteAttendeeTypeRequest
{
public HttpPostedFile PostedFile { get; set; }
public AttendeeType AttendeeType { get; set; }
public string LicenseNumber { get; set; }
public string LicenseState { get; set; }
public string SchoolName { get; set; }
public string SchoolLocation { get; set; }
}
【问题讨论】:
-
您可以使用
FormData。示例参考this answer -
@StephenMuecke — 不会提供 JSON 输出
-
@Quentin,不知道你在说什么。 OP 可以序列化表单或单独添加每个属性 - 例如
formdata.append(LicenseNumber, $("#txtLicenseNumber").val());等将绑定到控制器中的CompleteAttendeeTypeRequest模型。 -
@StephenMuecke — 请求被格式化为 application/json 而不是 multipart/form-data。您无法从 FormData 对象中获取 application/json。
-
OP 想要上传文件和属性,以便它们可以绑定到模型。它不需要是 JSON 输出 - 但它确实需要工作,这就是链接答案的作用:)
标签: javascript jquery json ajax asp.net-mvc-5