【发布时间】:2015-03-31 10:50:43
【问题描述】:
我需要使用 jquery ajax 将我的上传文件传递给我的控制器。
JS:
$('#btnpopupreg').click(function () {
$.ajax({
type: 'POST',
url: '/Membership/Register',
data: $('#frmRegister').serializeArray(),
dataType: 'json',
headers: fnGetToken(),
beforeSend: function (xhr) {
},
success: function (data) {
//do something
},
error: function (xhr) {
}
})
})
查看:
@model Test.RegisterViewModel
@{
using Html.BeginForm(Nothing, Nothing, FormMethod.Post, New With {.id = "frmPopUpRegister", .enctype = "multipart/form-data"})
}
<input type="file" />
//rest of my strongly typed model here
<input type="button" value="BUTTON" />
//rest of the code here
控制器:
[HttpPost()]
[AllowAnonymous()]
[ValidateAntiForgeryToken()]
public void Register(RegisterViewModel model)
{
if (Request.Files.Count > 0) { //always 0
}
if (ModelState.IsValid) {
//do something with model
}
}
我可以很好地获取模型值,但 Request.Files 总是返回 null。我也尝试过使用 HttpPostedFileBase 但它也总是返回 null
[HttpPost()]
[AllowAnonymous()]
[ValidateAntiForgeryToken()]
public void Register(RegisterViewModel model, HttpPostedFileBase files)
{
//files always null
if (ModelState.IsValid) {
//do something with model
}
}
【问题讨论】:
-
这个链接可能会回答你的问题[点击这里][1] [1]:stackoverflow.com/questions/2320069/jquery-ajax-file-upload
标签: c# jquery ajax asp.net-mvc