jQuery 通过 POST (ajax) 发送 JSON 数据并从 Controller (MVC) 接收 json 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8517071/
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-27 10:37:48  来源:igfitidea点击:

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

jqueryajaxasp.net-mvcjson

提问by Snake Eyes

I created a function in javascript like that:

我在 javascript 中创建了一个函数,如下所示:

function addNewManufacturer() {
       var name = $("#id-manuf-name").val();
       var address = $("#id-manuf-address").val();
       var phone = $("#id-manuf-phone").val();

       var sendInfo = {
           Name: name,
           Address: address,
           Phone: phone
       };

       $.ajax({
           type: "POST",
           url: "/Home/Add",
           dataType: "json",
           success: function (msg) {
               if (msg) {
                   alert("Somebody" + name + " was added in list !");
                   location.reload(true);
               } else {
                   alert("Cannot add to list !");
               }
           },

           data: sendInfo
       });
}

I called jquery.json-2.3.min.jsscript file and I used it for toJSON(array)method.

我调用了jquery.json-2.3.min.js脚本文件,并将其用于toJSON(array)方法。

In controller, I have this Addaction

在控制器中,我有这个Add动作

[HttpPost]
public ActionResult Add(PersonSheets sendInfo) {
    bool success = _addSomethingInList.AddNewSomething( sendInfo );

    return this.Json( new {
         msg = success
    });

}

But sendInfoas method parameter becomes null.

但是sendInfo随着方法参数变为空。

The model:

该模型:

public struct PersonSheets
{
    public int Id;
    public string Name;
    public string Address;
    public string Phone;
}

public class PersonModel
{
    private List<PersonSheets> _list;
    public PersonModel() {
         _list= GetFakeData();
    }

    public bool AddNewSomething(PersonSheets info) {
         if ( (info as object) == null ) {
            throw new ArgumentException( "Person list cannot be empty", "info" );
         }

         PersonSheets item= new PersonSheets();
         item.Id = GetMaximumIdValueFromList( _list) + 1;
         item.Name = info.Name;
         item.Address = info.Address;
         item.Phone = info.Phone;

         _list.Add(item);

         return true;
    }
}

How could I do in action method when the data was sent with POST ?

当使用 POST 发送数据时,我该怎么做?

I don't know how to use. Also, it is possible to send back the response (to ajax) via JSON ?

我不知道怎么用。此外,是否可以通过 JSON 发回响应(到 ajax)?

采纳答案by Praveen Prasad

Create a model

创建模型

public class Person
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
}

Controllers Like Below

像下面这样的控制器

    public ActionResult PersonTest()
    {
        return View();
    }

    [HttpPost]
    public ActionResult PersonSubmit(Vh.Web.Models.Person person)
    {
        System.Threading.Thread.Sleep(2000);  /*simulating slow connection*/

        /*Do something with object person*/


        return Json(new {msg="Successfully added "+person.Name });
    }

Javascript

Javascript

<script type="text/javascript">
    function send() {
        var person = {
            name: $("#id-name").val(),
            address:$("#id-address").val(),
            phone:$("#id-phone").val()
        }

        $('#target').html('sending..');

        $.ajax({
            url: '/test/PersonSubmit',
            type: 'post',
            dataType: 'json',
            contentType: 'application/json',
            success: function (data) {
                $('#target').html(data.msg);
            },
            data: JSON.stringify(person)
        });
    }
</script>

回答by Neha

var SendInfo= { SendInfo: [... your elements ...]};

        $.ajax({
            type: 'post',
            url: 'Your-URI',
            data: JSON.stringify(SendInfo),
            contentType: "application/json; charset=utf-8",
            traditional: true,
            success: function (data) {
                ...
            }
        });

and in action

并在行动

public ActionResult AddDomain(IEnumerable<PersonSheets> SendInfo){
...

you can bind your array like this

你可以像这样绑定你的数组

var SendInfo = [];

$(this).parents('table').find('input:checked').each(function () {
    var domain = {
        name: $("#id-manuf-name").val(),
        address: $("#id-manuf-address").val(),
        phone: $("#id-manuf-phone").val(),
    }

    SendInfo.push(domain);
});

hope this can help you.

希望这可以帮到你。

回答by Hiep Nguyen

Use JSON.stringify(<data>).

使用JSON.stringify(<data>).

Change your code: data: sendInfoto data: JSON.stringify(sendInfo). Hope this can help you.

更改您的代码:data: sendInfodata: JSON.stringify(sendInfo). 希望这可以帮到你。

回答by user1799669

To post JSON, you will need to stringify it. JSON.stringifyand set the processDataoption to false.

要发布 JSON,您需要对其进行字符串化。JSON.stringify并将processData选项设置为 false。

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

回答by Kirsten

Your PersonSheets has a property int Id, Idisn't in the post, so modelbinding fails. Make Id nullable (int?) or send atleast Id = 0 with the POst .

您的 PersonSheets 有一个 property int IdId不在帖子中,因此模型绑定失败。使 Id 可以为空(int?)或使用 POst 发送至少 Id = 0 。

回答by Abdul Munim

You don't need to call $.toJSONand add traditional = true

你不需要调用$.toJSON和添加traditional = true

data: { sendInfo: array },
traditional: true

would do.

会做。