2015-05-12 127 views
0

我想從我的視圖發送一堆表單數據並將其映射到我的控制器中的ViewModel參數。另外,我正嘗試發送一個文件,該文件將映射到一個單獨的參數。無法通過AJAX發送表單數據和文件上傳到控制器

formData被髮送到控制器時,它正確地將文件上傳映射到file參數,但是model參數屬性全爲空/默認值。

總之,我的問題是這樣的:我如何將我的表單元素值映射到我的控制器中的MyViewModel參數,同時發送文件呢?

型號:

public class MyViewModel 
{ 
    public int AsssumptionSetId { get; set; } 
    public int BuildingBlockId { get; set; } 
    public string ReplacementCode { get; set; } 
    public decimal Rounding { get; set; } 
    public string DataSource { get; set; } 
    public bool AER { get; set; } 
    public int Term { get; set; } 
} 

查看:

這種觀點是強類型的MyViewModel:

<form id="buildingBlockForm"> 

    @Html.HiddenFor(model => model.AsssumptionSetId) 
    @Html.HiddenFor(model => model.BuildingBlockId) 

    @Html.TextBoxFor(m => m.ReplacementCode) 

    @Html.TextBoxFor(m => m.Rounding) 

    @Html.DropDownListFor(m => m.DataSource, (SelectList)ViewBag.DataSources) 

    @Html.DropDownListFor(m => m.Term, (SelectList)ViewBag.Terms) 

    @Html.CheckBoxFor(m => m.AER) 

    <input type="file" id="file" name="file" /> 

    <input class="button green-button" type="submit" value="Create" /> 

</form> 

控制器:

public ActionResult CreateBuildingBlock(MyViewModel model, HttpPostedFileBase file) 
     { 
      // all of the 'model' properties = null instead of the form values 
      // file = the file I chose to upload and works as expected 
     } 

JS:

var formData = new FormData($('#buildingBlockForm')); 

// Get file and append to form data (Should only be 1) 
$.each(Files["csv"], function (key, value) { 
    formData .append("file", value); 
}); 

// Send file 
$.ajax({ 
    url: '/Assumptions/CreateBuildingBlock', 
    type: 'POST', 
    data: formData, 
    cache: false, 
    dataType: "json", 
    contentType: false, 
    processData: false, 

    success: function (response) { 
     // Handle success 
    }, 
    error: function (xhr, status, errorThrown) { 
     // Handle errors 
    } 
}); 
+0

這個方法還會發送文件嗎? – Tomuke

+1

你嘗試新的FormData($('#buildingBlockForm')[0]); –

+0

'新的FormData($('#buildingBlockForm')[0]);'是它!謝謝!你能解釋爲什麼這是必要的嗎?張貼答案@DennisCheung,我會接受。 – Tomuke

回答

1

原來我在抓取需要序列化的表單時缺少索引。

new FormData($('#buildingBlockForm')[0]); 

這解決了我的問題。

+0

非常感謝你! –

0

,因爲你的表單包含一個文件輸入型,你需要你的形式來處理此提交(加密類型)。

<form id="buildingBlockForm" enctype="multipart/form-data"> 

另外,如果你想堅持MVC的形式幫手,它會減輕你可能有一個基於腳本的AJAX後的問題。

@using (Ajax.BeginForm("CreateBuildingBlock", "Assumptions", null, new AjaxOptions { HttpMethod = "POST", OnSuccess = "postSuccess", OnFailure = "postFailed" }, new { enctype = "multipart/form-data" })) 
{ 
    // your form fields here 
} 

<script> 
    function postSuccess() { 
    // handle success here 
    } 

    function postfailed() { 
    // handle failed post here 
    } 
</script> 
+0

不幸的是,這個問題不在於文件發佈和映射到它的參數,因爲這可以正常工作。問題是剩餘的表單值沒有映射到ViewModel對象參數。 – Tomuke

+0

您是否按照建議使用表單的類型進行嘗試?我知道你有一個成功的帖子,提供了@丹尼斯的建議,但對於我爲何添加[0]解決您的問題沒有任何意義。 – Eckert

+0

是的,建議的解決方案可以很好地處理和不用表單類型。 – Tomuke

相關問題