我想弄清楚如何從窗體發送一些信息到Web API操作。這是jQuery的/ AJAX我試圖使用方法:發送JSON對象到Web API
var source = {
'ID': 0,
'ProductID': $('#ID').val(),
'PartNumber': $('#part-number').val(),
'VendorID': $('#Vendors').val()
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/PartSourceAPI/",
data: JSON.stringify({ model: source }),
success: function (data) {
alert('success');
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
這裏是我的模型
public class PartSourceModel
{
public int ID { get; set; }
public int ProductID { get; set; }
public int VendorID { get; set; }
public string PartNumber { get; set; }
}
這是我的看法
<div id="part-sources">
@foreach (SmallHorse.ProductSource source in Model.Sources)
{
@source.ItemNumber <br />
}
</div>
<label>Part Number</label>
<input type="text" id="part-number" name="part-number" />
<input type="submit" id="save-source" name="save-source" value="Add" />
這裏是我的控制器操作
// POST api/partsourceapi
public void Post(PartSourceModel model)
{
// currently no values are being passed into model param
}
我錯過了什麼?現在當我調試並且在ajax請求觸發控制器動作時執行此操作時,沒有任何內容被傳遞到模型參數中。
你沒有'JSON.stringify'嘗試? 'data:{model:source}',或者可能只是'data:source' - jQuery爲你處理轉換... – nnnnnn
是的,我沒有使用JSON.stringify來嘗試它,但那也不起作用。我已經嘗試了所有可能的AJAX方面的組合,但我認爲我在控制器上缺少了一些東西......但我不知道,這純粹是一種猜測。 – Cory
當你說「沒有」被傳入模型參數時,你的意思是實例「model」是否爲null?或者它的值是否爲默認值/空值?如果將模型類型更改爲字符串以獲取原始表示,甚至刪除輸入參數並直接探測Request.Content和Request.Headers屬性以找出服務器正在接收的內容,會發生什麼情況? – Snixtor