使用asp .net mvc中的jquery将文件作为参数传递

时间:2014-11-19 14:48:48

标签: javascript jquery ajax asp.net-mvc

为了从文件excel导入数据并在ascx页面中显示数据,我想通过jQuery函数将文件作为参数传递给控制器 这是我的代码: 查看:

<% Using (Html.BeginForm (new {enctype = "multipart / form-data"}))
                     {%>
                         <input type = "file" name = "file" />
                         <input type = "button" value = "OK" onclick = "Import (); return false;" />
                     <%}%>

jquery的:

Import function () {
     var formData = new FormData ();
     formData = do something to get the file
     var Dialog = new MessageBox ();
     $ .ajax ({
         the type: 'POST'
         url: "/ Controller / Import"
         data: formData,
         cache: false,
         contentType: false,
         processData: false,
         success: function (View) {
             alert ("success");
             $ ("# DivList"). Empty ()
             $ ("# mainPageMainContent") append (View).;
         },
         complete: function () {
             ClosePatienter ();
             Dialog.MsgClose ();
         }
     });
}

控制器:

public ActionResult Import(HttpPostedFileBase file)
{
      ......
      return PartialView("OtherView", model);
}

当我执行此操作时,我的控制器中的文件为空 有人可以帮助我 提前谢谢你

1 个答案:

答案 0 :(得分:0)

您没有将文件添加到formdata obj。做这样的事情:

var formData = new FormData ();
//formData = do something to get the file
var uploadField = document.getElementById('uploadField');
formData.append("file", uploadField.files[0]);

其中“uploadField”是文件输入元素的id。