Partial view Asp.Net Mvc ajax download?

Is it possible to download ajax file with partial view?

I am trying to do the 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 do not know what types of parameters I should pass to the controller action. I debugged this with this situation.

galeryId = 1;
formElements = "";
files = null;

If this is possible (loading an ajax file with partial views), how can I do this?

Thank.

+2
source share
1 answer

A serialized approach will not work with file uploads (input file types are ignored). Depending on your target browsers, you can use the FormData approach (for IE it should be 10+) or start playing with iframes to publish your form asynchronously.

+1

All Articles