2

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
  • 1
    you can't use $.Ajax to post file.if you want async upload u must use plugins like Uploadify. Commented Dec 9, 2012 at 15:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.