发送JSON对象的Web API [英] Sending JSON object to Web API
本文介绍了发送JSON对象的Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找出如何从一种形式发送一些信息到一个Web API的动作。这是jQuery的/ AJAX我试图使用方法:
I am trying to figure out how I can send some information from a form to a Web API action. This is the jQuery/AJAX I'm trying to use:
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请求到达控制器动作没有什么被传递到模型参数。
What am I missing? right now when I debug and step through this when the ajax request hits the controller action there is nothing being passed into the model param.
推荐答案
试试这个:
的jQuery
$('#save-source').click(function (e) {
e.preventDefault();
var source = {
'ID': 0,
//'ProductID': $('#ID').val(),
'PartNumber': $('#part-number').val(),
//'VendorID': $('#Vendors').val()
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/PartSourceAPI",
data: source,
success: function (data) {
alert(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
//jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
});
控制器
public string Post(PartSourceModel model)
{
return model.PartNumber;
}
查看
<label>Part Number</label>
<input type="text" id="part-number" name="part-number" />
<input type="submit" id="save-source" name="save-source" value="Add" />
现在,当您点击添加
'您填写后的文本框中,将控制器
会吐回了你在部分号码
框警报写道。
Now when you click 'Add
' after you fill out the text box, the controller
will spit back out what you wrote in the PartNumber
box in an alert.
这篇关于发送JSON对象的Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文