我正在尝试将带有ajax和Jquery的formdata fileupload传递给我的控制器。
但是当我在控制器中时,Request.files.count是0 ??
我错过了什么?
视图文件
<div class="form-group">
@Html.LabelFor(model => model.ImageFile)
<!-- Example file element -->
<input type="file" name="FileUpload1" id="FileUpload1" />
</div>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('#loginButton').click(function (e) {
e.preventDefault();
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload1").files.length;
var file = document.getElementById("FileUpload1").files[0];
formData.append("FileUpload", file);
alert(totalFiles);
alert(file);
$.ajax({
type: "POST",
url: '/Manage/GetPartialView)',
data: $formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (result) {
alert(result);
},
});
});
});
控制器
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult GetPartialView(Listing listing)
{
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
if (ModelState.IsValid)
{
db.Listings.Add(listing);
db.SaveChanges();
}
return PartialView("_ProfileCreateListingsPartial");
}
希望有人可以帮我解决这个问题 /蒂娜
答案 0 :(得分:2)
使用此:
jQuery(document).ready(function ($) {
$('#loginButton').click(function (e) {
e.preventDefault();
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload1").files.length;
var file = document.getElementById("FileUpload1").files[0];
formData.append("FileUpload", file);
alert(totalFiles);
alert(file);
$.ajax({
type: "POST",
url: '/Manage/GetPartialView',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (result) {
alert(result);
},
});
});
});