我正在尝试找出如何将表单中的一些信息发送到Web API操作。这是我正在尝试使用的jQuery / AJAX:
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