Enviar datos JSON vía POST (ajax) y recibir respuesta json del Controlador (MVC)


He creado una función en javascript como esta:

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

Llamé a jquery.json-2.3.min.js archivo de script y lo usé para el método toJSON(array).

En el controlador, tengo esta Add acción

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

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

}

Pero sendInfo como parámetro de método se convierte en null.

El modelo:

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

¿Cómo podría hacer en el método de acción cuando los datos se enviaron con POST ?

No se como usar. Además, es posible enviar de vuelta la respuesta (a ajax) a través de JSON ?

Gracias

Author: Sayyid, 2011-12-15

5 answers

Crear un modelo

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

Controladores Como Abajo

    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>
 84
Author: Praveen Prasad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-12 15:27:09
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) {
                ...
            }
        });

Y en acción

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

Puede enlazar su matriz de esta manera

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

Espero que esto pueda ayudarte.

 120
Author: Neha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-09 09:49:23

Use JSON.stringify(<data>).

Cambie su código: data: sendInfo a data: JSON.stringify(sendInfo). Espero que esto pueda ayudarte.

 8
Author: Hiep Nguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-09 09:46:40

Su PersonSheets tiene una propiedad int Id, Id no está en el post, por lo que modelbinding falla. Hacer id nullable (int?) o enviar atleast Id = 0 con el mensaje .

 0
Author: Kirsten,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-27 14:13:04

No es necesario llamar a $.toJSON y agregar traditional = true

data: { sendInfo: array },
traditional: true

Lo haría.

 -2
Author: Abdul Munim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-15 08:46:04