Upload is null after adding jquery.unobtrusive-ajax.js reference

牧云@^-^@ 提交于 2019-11-30 09:16:20

问题


If I don't refer jquery.unobtrusive-ajax.js I can get attachment on Post. If I refer it It's giving me 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); 
                ......

How to handle this?


回答1:


I modify the jquery.unobtrusive-ajax.js to work uploading files. First modification:

$(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
        });
    });

Second modification is in 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 });
    }
}
...



回答2:


If you don't refer jquery.unobtrusive-ajax.js, you don't get the ajax form, but a regular HTML form. And if you do, I suppose the form works fine, but it is not possible to upload a file with it, as ajax does not allow multipart/form-data enctype.

You can use HTML 5 File API (Using files from web applications) or jQuery upload plugins.



来源:https://stackoverflow.com/questions/20643512/upload-is-null-after-adding-jquery-unobtrusive-ajax-js-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!