通过POST (ajax)发送JSON数据并接收来自控制器(MVC)的JSON响应

时间:2022-02-20 18:13:50

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.js script file and I used it for toJSON(array) method.

我叫jquery.json-2.3.min。js脚本文件,我将它用于toJSON(数组)方法。

In controller, I have this Add action

在控制器中,我有这个Add action

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

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

}

But sendInfo as method parameter becomes null.

但是sendInfo作为方法参数变为null。

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) ?

Thank you

谢谢你!

5 个解决方案

#1


76  

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

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

#2


118  

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.

希望这能对你有所帮助。

#3


7  

Use JSON.stringify(<data>).

使用JSON.stringify( <数据> )。

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

更改代码:数据:sendInfo数据:JSON.stringify(sendInfo)。希望这能对你有所帮助。

#4


0  

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

您的PersonSheets有一个属性int Id, Id不在post中,所以modelbinding失败。让Id为nullable (int?),或者发送至少Id = 0。

#5


-2  

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

你不需要调用$。toJSON并添加传统= true

data: { sendInfo: array },
traditional: true

would do.

要做的事情。

#1


76  

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

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

#2


118  

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.

希望这能对你有所帮助。

#3


7  

Use JSON.stringify(<data>).

使用JSON.stringify( <数据> )。

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

更改代码:数据:sendInfo数据:JSON.stringify(sendInfo)。希望这能对你有所帮助。

#4


0  

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

您的PersonSheets有一个属性int Id, Id不在post中,所以modelbinding失败。让Id为nullable (int?),或者发送至少Id = 0。

#5


-2  

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

你不需要调用$。toJSON并添加传统= true

data: { sendInfo: array },
traditional: true

would do.

要做的事情。