是否有可能AJAX文件上传与局部视图?
Is it possible ajax file upload with partial views?
我尝试用下面的做到这一点:
I try to do this with following:
_Upload.cshtml(PartialView)
<script type="text/javascript">
$(document).ready(function () {
$("#upload").click(function () {
var val = $("#galeries").val();
if (val == null || val == "") {
val = 0;
}
var form = $("#form");
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: { galeryId: val, formElements: form.serialize() },
complete: function () {
},
error: function (jqXhr, textStatus, errorThrown) {
alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
},
success: function (data) {
}
});
});
});
</script>
@using (Html.BeginForm("_Upload", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "form" }))
{
<input type="file" name="file" id="file" />
<input type="button" value="Yükle" id="upload" />
}
控制器
[HttpPost]
public ActionResult _Upload(IEnumerable<HttpPostedFileBase> files, int galeryId,FormCollection formElements)
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/Galery_" + galeryId), fileName);
file.SaveAs(path);
}
}
return View();
}
我不知道,哪个参数类型,我应该传给控制器动作。我调试它这样的情况。
I dont know, Which parameter types, I should pass to controller action. I debugged it with this situation.
galeryId = 1;
formElements = "";
files = null;
如果有可能(阿贾克斯文件上传与局部视图),我该怎么办?
If it is possible (ajax file upload with partial views), How Can I do?
感谢。
本连载的方式将不能与文件上传工作(文件输入类型被忽略)。根据你的目标浏览器,您可以使用 FORMDATA 办法(IE浏览器一定是10+),或开始播放内置页框来发表您的形式异步的。
The serialize approach won't work with file uploads (file input types are ignored). Depending on your target browsers, you can use the FormData approach (for IE it must be 10+), or start playing with iframes to post your form asynchronously.