【问题标题】:How to upload file using ajax.beginform in asp.net MVC如何在 asp.net MVC 中使用 ajax.beginform 上传文件
【发布时间】:2024-05-20 03:45:02
【问题描述】:

我的看法:

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

【问题讨论】:

  • 包含new { enctype = "multipart/form-data" } html 属性
  • 试过也不能用它
  • 您无法使用 AJAX 上传文件 - *.com/questions/17037948/…

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


【解决方案1】:

基本上您不能使用 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/

【讨论】:

    【解决方案2】:

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

    【讨论】:

      最近更新 更多