如何在asp.net MVC中使用ajax.beginform上传文件

时间:2015-06-15 07:22:38

标签: jquery asp.net-mvc-4 asp.net-ajax asyncfileupload

我的观点:

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文件中没有上传,我们可以在这里找到其他任何解决方案吗?

2 个答案:

答案 0 :(得分:0)

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/

答案 1 :(得分:0)

使用这个我们可以用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;
});