如何使用javascript将文件类型值传递给控制器

时间:2014-12-05 11:59:48

标签: javascript ajax asp.net-mvc-4

我在视图中有输入类型文件控件,我想将选定的附件发送给控制器。

但是,如下所示,Controller动作中的文件参数值始终为空。

请告诉我如何使用ajax将文件详细信息发送到控制器。

查看:

<div>
  @Html.DropDownListFor(model => model.IDdocument, IdList, new { id = "ddlFileType" })
  @Html.TextBoxFor(model => model.Description, new { id = "txtDescription" })
  @Html.TextBoxFor(model => model.Attachment, new { type = "file", id="txtFile" })
  @Html.ActionLink("Add", "", "ESignature", new { }, new { id = "lnkAddAttachment" })
</div> 

JavaScript的:

 $("#lnkAddAttachment").click(function (e) {
    var fileType = document.getElementById("ddlFileType").value;
    var desc = document.getElementById("txtDescription").value;
    var selectedFile = document.getElementById('txtFile').files[0];

    var url = '@Url.Content("~/")' + "ESignature/AddAttachment?type=" + fileType + "&desc=" + desc + "&file=" + selectedFile;

    $.ajax({
        url: url,
        data: $('#frmRegistration').serialize(),
        type: 'GET',
        success: function () {                  
            var url = '@Url.Content("~/")' + "ESignature/Registration"
            $('#gridAttachments').load(url+' #gridAttachments')
        }
    });
    return false;
})

控制器:

[HttpGet]
public ActionResult AddAttachment(BRUser brUser, string type, string desc, HttpPostedFileBase file)
{
     // Here I am getting all values except for file parameter
}

型号:

public class BRUser
{
    public string IDdocument { get; set; }
    public string Description { get; set; }
    public HttpPostedFileBase Attachment { get; set; }
 }

0 个答案:

没有答案