2015-09-26 39 views
3

我有一個ASP.NET MVC 5應用程序。我試圖用模型數據發送POST請求,並且還包括用戶選擇的文件。 這是我的視圖模型(爲了清楚而簡化):如何在MVC 5中的單個Ajax POST請求中發送ViewModel和文件?

public class Model 
{ 
    public string Text { get; set; } 
    public long Id { get; set; } 
} 

這裏是控制器的操作:

[HttpPost] 
public ActionResult UploadFile(long userId, Model model) 
{ 
    foreach (string file in Request.Files) 
    { 
     // process files 
    } 

    return View("Index"); 
} 

HTML輸入元件:

<div> 
    <input type="file" name="UploadFile" id="txtUploadFile" /> 
</div> 

和JavaScript代碼:

$('#txtUploadFile').on('change', function (e) { 
    var data = new FormData(); 
    for (var x = 0; x < files.length; x++) { 
     data.append("file" + x, files[x]); 
    } 
    data.append("userId", 1); 
    data.append("model", JSON.stringify({ Text: 'test text', Id: 3 })); 

    $.ajax({ 
     type: "POST", 
     url: '/Home/UploadFile', 
     contentType: false, 
     processData: false, 
     data: data, 
     success: function (result) { }, 
     error: function (xhr, status, p3, p4) { } 
    }); 
}); 

問題是,當請求達到控制器操作時,我填充了文件和'userId',但'模型'參數始終爲空。填充FormData對象時我做錯了什麼?

+1

W¯¯什麼ith contentType:「application/json」它不會發送文件。 –

+1

參考[這個答案](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681 ) - 而不是'data.append(「model」,JSON.stringify({Text:'test text',Id:3}));'它應該是'data.append(Text,'test text'); data.append(Id,3);' –

+0

謝謝,現在我看到了FormData的問題! –

回答

3

這裏是我的測試使用與MVC5和IE11 /鉻

查看

<script> 
    $(function() { 
     $("#form1").submit(function() { 
      /*You can also inject values to suitable named hidden fields*/ 
      /*You can also inject the whole hidden filed to form dynamically*/ 
      $('#name2').val(Date); 
      var formData = new FormData($(this)[0]); 
      $.ajax({ 
       url: $(this).attr('action'), 
       type: $(this).attr('method'), 
       data: formData, 
       async: false, 
       success: function (data) { 
        alert(data) 
       }, 
       error: function(){ 
        alert('error'); 
       }, 
       cache: false, 
       contentType: false, 
       processData: false 
      }); 
      return false; 
     }); 
    }); 
</script> 

<form id="form1" action="/Home/Index" method="post" enctype="multipart/form-data"> 
    <input type="text" id="name1" name="name1" value="value1" /> 
    <input type="hidden" id ="name2" name="name2" value="" /> 
    <input name="file1" type="file" /> 
    <input type="submit" value="Sublit" /> 
</form> 

控制器

public class HomeController : Controller 
{ 
    [HttpGet] 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index(HttpPostedFileBase file1, string name1, string name2) 
    { 
     var result = new List<string>(); 
     if (file1 != null) 
      result.Add(string.Format("{0}: {1} bytes", file1.FileName, file1.ContentLength)); 
     else 
      result.Add("No file"); 
     result.Add(string.Format("name1: {0}", name1)); 
     result.Add(string.Format("name2: {0}", name2)); 
     return Content(string.Join(" - ", result.ToArray())); 
    } 
} 

感謝Silver89他answer

+0

問題是我沒有窗體上的所有必填字段,因此模型是在發送POST請求之前使用JS代碼構建的。 –

+0

@IgorGoroshko我認爲有很多方法可以解決這個問題,您可以測試的方法是將您的值注入合適的命名隱藏字段中。 –

+0

@IgorGoroshko已更新爲在隱藏字段中注入值。 –