添加jquery.unobtrusive-ajax.js引用后,Upload为null

时间:2013-12-17 19:59:21

标签: 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); 
                ......

如何处理?

2 个答案:

答案 0 :(得分:2)

如果您不引用jquery.unobtrusive-ajax.js,则不会获得ajax表单,而是常规HTML表单。如果你这样做,我认为表单工作正常,但是无法用它上传文件,因为ajax不允许multipart/form-data enctype。

您可以使用HTML 5文件API(Using files from web applications)或jQuery上传插件。

答案 1 :(得分:2)

我修改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 });
    }
}
...