close

form 先設定 enctype 是 multipart/form-data 如下

<form name="form1" id="form1" enctype="multipart/form-data">

抓取表單時使用FormData

var postData = new FormData($("#form1")[0]); 

這樣丟到 Controller 就不會造成HttpPostedFileBase 會是null

   1: var postData = new FormData($("#form1")[0]);
   2:            $.ajax({
   3:                    url: ajaxurl,
   4:                    type: "POST",
   5:                    data: postData,
   6:                    cache: false,
   7:                    dataType: 'json',
   8:                    processData: false, 
   9:                    contentType: false, 
  10:                    success: function (data) {
  11:                        console.log(data)
  12:                        if (data.Msg == "success") {
  13:                            Message("儲存成功!");
  14:                            location.href = "@Url.Action("Index")";
  15:                        }
  16:                        else {
  17:                            Message("儲存失敗!" + data.Msg);
  18:                            return false;
  19:                        }
  20:                    }
  21:                });
  22:             }
  23:            });


Controller的操作如下

   1: [HttpPost]
   2:  
   3:  public JsonResult Add(FormCollection formCollection, HttpPostedFileBase file)
   4:  
   5: {
   6:  
   7:  var Name = formCollection["name"];
   8:  
   9:   file.SaveAs(filePath);
  10:  
  11: }
arrow
arrow
    文章標籤
    C# mvc ASP.NET jQuery
    全站熱搜

    baechang 發表在 痞客邦 留言(0) 人氣()