Как загрузить файл с помощью ajax.beginform в asp.net MVC

Мой взгляд:

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

Контроллер:

[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. 
}

Я думаю, что в ajax.beginform файл не загружен, может у нас есть какое-то другое решение?


person rohit singh    schedule 15.06.2015    source источник
comment
Включите атрибут new { enctype = "multipart/form-data" } html   -  person    schedule 15.06.2015
comment
пробовал и с этим не работает   -  person rohit singh    schedule 15.06.2015
comment
Вы не можете загрузить файл с помощью AJAX - stackoverflow.com/questions/17037948/   -  person ramiramilu    schedule 15.06.2015


Ответы (2)


В основном вы не можете загружать с помощью AJAX, поскольку он не поддерживается, однако вы можете использовать некоторые плагины, такие как Ajax Upload и Uploadify. Многие из них можно найти здесь: http://www.sitepoint.com/10-jquery-ajax-file-uploader-plugins/

Вы также можете следовать этому руководству: http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/

person Nilmag    schedule 15.06.2015

Используя это, мы можем получить файл в форме ajax.begin.

$("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;
});
person Karan Singh    schedule 12.10.2017