Asp.Net Mvc ajax file upload with partialViews?

て烟熏妆下的殇ゞ 提交于 2020-01-13 19:51:16

问题


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" />
}

CONTROLLER

[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?

Thanks.


回答1:


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.



来源:https://stackoverflow.com/questions/13788372/asp-net-mvc-ajax-file-upload-with-partialviews

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!