我想弄清楚如何从窗体发送一些信息到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