jQuery 将 JSON 对象发送到 Web API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13870161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:02:23  来源:igfitidea点击:

Sending JSON object to Web API

c#-4.0jqueryasp.net-mvc-4asp.net-web-api

提问by Cory

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:

我想弄清楚如何将一些信息从表单发送到 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 });
        }
    });

Here is my model

这是我的模型

public class PartSourceModel
{
    public int ID { get; set; }
    public int ProductID { get; set; }
    public int VendorID { get; set; }
    public string PartNumber { get; set; }
}

Here is my view

这是我的观点

<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" />

Here is my controller action

这是我的控制器操作

// POST api/partsourceapi
public void Post(PartSourceModel model)
{
    // currently no values are being passed into model param
}

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.

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

回答by mnsr

Try this:

尝试这个:

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 });
            }
        });
    });

Controller

控制器

    public string Post(PartSourceModel model)
    {
        return model.PartNumber;
    }

View

看法

<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 controllerwill spit back out what you wrote in the PartNumberbox in an alert.

现在,当您Add在填写完文本框后单击“ ”时,controller它将PartNumber以警报形式吐出您在框中所写的内容。

回答by Jeroen

Change:

改变:

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

To:

到:

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

And in your controller you do this:

在你的控制器中你这样做:

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

   var result = js.Deserialize<PartSourceModel>(model);
}

If the url you use in jquery is /api/PartSourceAPIthen the controller name must be apiand the action(method) should be PartSourceAPI

如果您在 jquery 中使用的 url 是/api/PartSourceAPI控制器名称api,则操作(方法)应该是PartSourceAPI

回答by Ashot

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}"

your data is something like this "{"model": "ID":0,"ProductID":6,"PartNumber":7,"VendorID":8}}" web api controller cannot bind it to Your model

您的数据是这样的 "{"model": "ID":0,"ProductID":6,"PartNumber":7,"VendorID":8}}" web api 控制器无法将其绑定到您的模型

回答by Andrés Nava - Azure

I believe you need quotes around the model:

我相信您需要引用以下内容model

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