Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 4.0 将JSON对象发送到Web API_C# 4.0_Jquery_Asp.net Mvc 4_Asp.net Web Api - Fatal编程技术网

C# 4.0 将JSON对象发送到Web API

C# 4.0 将JSON对象发送到Web API,c#-4.0,jquery,asp.net-mvc-4,asp.net-web-api,C# 4.0,Jquery,Asp.net Mvc 4,Asp.net Web Api,我试图弄清楚如何将一些信息从表单发送到Web API操作。这是我尝试使用的jQuery/AJAX: var source = { 'ID': 0, 'ProductID': $('#ID').val(), 'PartNumber': $('#part-number').val(), 'VendorID': $('#Vendors').val() } $.ajax({ type: "POST",

我试图弄清楚如何将一些信息从表单发送到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" />

我错过了什么?现在,当我调试并逐步执行此操作时,当ajax请求点击控制器操作时,没有任何内容被传递到模型参数。

我相信您需要在
模型周围加上引号:

JSON.stringify({ "model": source })
更改:

 data: JSON.stringify({ model: source })
致:

在控制器中,您可以执行以下操作:

public void PartSourceAPI(string model)
{
       System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

   var result = js.Deserialize<PartSourceModel>(model);
}
public void PartSourceAPI(字符串模型)
{
System.Web.Script.Serialization.JavaScriptSerializer js=new System.Web.Script.Serialization.JavaScriptSerializer();
var result=js.反序列化(模型);
}
如果您在jquery中使用的url是
/api/PartSourceAPI
,那么控制器名称必须是
api
,操作(方法)应该是
PartSourceAPI
尝试以下操作:

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" />
零件号
现在,当您填写文本框后单击“
Add
”时,
controller
将在警报中吐出您在
PartNumber
框中写下的内容

var model = JSON.stringify({ 
    'ID': 0, 
    'ProductID': $('#ID').val(), 
    'PartNumber': $('#part-number').val(),
    'VendorID': $('#Vendors').val()
})

$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    url: "/api/PartSourceAPI/",
    data: model,
    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 });
    }
});

var model = JSON.stringify({      'ID': 0,     ...': 5,      'PartNumber': 6,     'VendorID': 7 }) // output is "{"ID":0,"ProductID":5,"PartNumber":6,"VendorID":7}"
您的数据类似于“{”模型“:“ID”:0,“ProductID”:6,“PartNumber”:7,“VendorID”:8}”
web api控制器无法将其绑定到您的模型

您是否尝试过不使用JSON.stringify
<代码>数据:{model:source},或者可能只是
数据:source
-jQuery为您处理转换…是的,我在没有JSON.stringify的情况下尝试过它,但也不起作用。在AJAX方面,我已经尝试了我能想到的所有可能的组合,但我认为控制器上缺少了一些东西。。但我不知道,这纯粹是猜测。当你说“nothing”被传递到model参数时,你是说实例“model”为null吗?或者它的值是默认值/空值?如果将模型类型更改为字符串以获取原始表示,会发生什么情况,或者甚至删除输入参数并直接探测Request.Content和Request.Headers属性以了解服务器正在接收什么?在对象文本中,如果属性名称是数字文本或有效标识符名称,则不需要引用属性名称。因此,
{model:source}
很好。您是否使用浏览器的调试器工具检查发送到请求正文中的操作方法的内容?Queti,是的,我使用的是Fiddler,它说没有随请求一起发送内容。我尝试使用引号,与您完全一样,但没有任何区别。@z00l-您只需要JSON的引号,而这不是。对象文本和JSON不是一回事。我试过了,但不幸的是没有任何区别。谢谢!只需更改
data:source
即可修复它,使其正确绑定到控制器中的“model”参数。我想我必须在我的ajax中包含“model:”这个名称,这样它才能工作。谢谢!对于复杂的数据格式(默认情况下不能反序列化),您需要在服务器端接收json字符串。你的答案可能适用于简单的数据,但不适用于复杂的数据(这就是我搜索的哈哈)。不过,你的答案对这个男人的问题很好!我发现我必须在ajax调用中包含
contentType:'application/json'
。为什么这个答案不需要它?
<label>Part Number</label>
<input type="text" id="part-number" name="part-number" />

<input type="submit" id="save-source" name="save-source" value="Add" />
var model = JSON.stringify({ 
    'ID': 0, 
    'ProductID': $('#ID').val(), 
    'PartNumber': $('#part-number').val(),
    'VendorID': $('#Vendors').val()
})

$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    url: "/api/PartSourceAPI/",
    data: model,
    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 });
    }
});

var model = JSON.stringify({      'ID': 0,     ...': 5,      'PartNumber': 6,     'VendorID': 7 }) // output is "{"ID":0,"ProductID":5,"PartNumber":6,"VendorID":7}"