How to upload file using ajax.beginform in asp.net MVC

5.6k views Asked by At

My view:

using (Ajax.BeginForm("Create", "CustomerEngagement", null, new AjaxOptions { OnSuccess = "closePopUpAndShowNextPost", InsertionMode = InsertionMode.Replace, HttpMethod = "post" }, new { @id = "create" }))
{
    // Lots of things going on here 
    // I need to implement fileupload to upload attachments asynchronously here 
    <input name="fileupload1" id="fileupload1" multiple type="file" />
    <button id="fileupload" name = "upload">
    //Button to submit the form
    <button id="save" value="save">
}

Controller :

[HttpPost]
public ActionResult Create(string word, StudentModel model)
{
    List<string> synonyms = new List<string>();
    List<string> sugg = new List<string>();
    //Doing lot of stuff here
    // I'm trying to get httppostedfilebase here but its null, also request.Files[] coming null. 
}

I think in ajax.beginform file is not uploaded, can we have any other solution here?

2

There are 2 answers

0
Nilmag On

Basically you cannot upload using AJAX as it is not supported, you can however use some plugins such as Ajax Upload and Uploadify. Many of which are found here: http://www.sitepoint.com/10-jquery-ajax-file-uploader-plugins/

You can also follow this tutorial: http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/

0
Karan Singh On

Using this we can get the file in ajax.begin form

$("body").on("submit", "#frmAddEditProcess", function (e) {
    var form = e.target;
    if (form.dataset.ajax) {
        e.preventDefault();
        e.stopImmediatePropagation();
        var xhr = new XMLHttpRequest();
        xhr.open(form.method, form.action);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                if (form.dataset.ajaxUpdate) {
                    var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
                    if (updateTarget) {
                        updateTarget.innerHTML = xhr.responseText;
                        OnEmployeeCertificationSuccess();
                    }
                }
            }
        };
        if ($("#frmAddEditProcess").valid()) { xhr.send(new FormData(form)); }
    } return true;
});