我想從我的視圖發送一堆表單數據並將其映射到我的控制器中的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
}
});
這個方法還會發送文件嗎? – Tomuke
你嘗試新的FormData($('#buildingBlockForm')[0]); –
'新的FormData($('#buildingBlockForm')[0]);'是它!謝謝!你能解釋爲什麼這是必要的嗎?張貼答案@DennisCheung,我會接受。 – Tomuke