c# - 添加jquery.unobtrusive-ajax.js引用后上传为空

标签 c# jquery ajax asp.net-mvc unobtrusive-ajax

如果我不引用 jquery.unobtrusive-ajax.js 我可以在 Post 上获取附件。如果我引用它,它会给我 null。

<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>


@using (Ajax.BeginForm("Index", "ContactSubmission", new AjaxOptions{ InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnSuccess = "updateSuccess" },
     new { enctype = "multipart/form-data",@class = "form-horizontal", role = "form" }))
      {
               ///code here

[HttpPost]
public JsonResult Index(Contact contact)
{
    if (ModelState.IsValid)
    {
       if (contact != null)
       {
         string attachment = string.Empty;
         // HttpPostedFileBase Attachment
         if (contact.Attachment != null) attachment = SaveFile(contact.Attachment); 
                ......

如何处理?

最佳答案

我修改了 jquery.unobtrusive-ajax.js 来上传文件。 第一次修改:

$(document).on("submit", "form[data-ext=true]", function (evt) {
        var clickInfo = $(this).data(data_click) || [],
            clickTarget = $(this).data(data_target),
            isCancel = clickTarget && clickTarget.hasClass("cancel");
        evt.preventDefault();
        if (!isCancel && !validate(this)) {
            return;
        }
        var formData;
        if (this.enctype && this.enctype === "multipart/form-data") {
            formData = new FormData(this);
        } else {
            formData = clickInfo.concat($(this).serializeArray());
        }

        asyncRequest(this, {
            url: this.action,
            type: this.method || "GET",
            data: formData
        });
    });

第二次修改在asyncRequest中:

....
method = options.type.toUpperCase();
if (options.data instanceof FormData) {
    options.processData = false;
    options.contentType = false;
    options.data.append("X-Requested-With", "XMLHttpRequest");

    if (!isMethodProxySafe(method)) {
        options.type = "POST";
        options.data.append("X-HTTP-Method-Override", method);
    }
} else {
    options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });

    if (!isMethodProxySafe(method)) {
        options.type = "POST";
        options.data.push({ name: "X-HTTP-Method-Override", value: method });
    }
}
...

关于c# - 添加jquery.unobtrusive-ajax.js引用后上传为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20643512/

相关文章:

javascript - 为什么我不能从 jQuery/AJAX 调用这个 PHP 文件?

c# - WebRequest.GetResponse 锁定?

c# - 以下 DateTime/TimeZone 示例有什么问题?

c# - 如何在 C# 中声明一个包含固定数量固定大小字符串的数组?

c# - 将代码作为参数C#传递

ruby-on-rails - 使用 jquery ajax 通过 form_for 中的链接渲染部分

javascript - 无法使用 columnFilter 重新初始化 DataTable 错误

javascript - 使用不同版本的 jQuery

javascript - jQuery :not with anchor exclude div and img elements

jQuery X-可编辑 : Update select field based on value of other select field