Juan Erroa
Juan Erroa

Reputation: 45

How to return a model to ajax call in MVC 5

My goal is restrict some inputs with the data from another table so I'm trying to do it with an ajax call.

This is the controller:

[HttpPost]
    public JsonResult getProductbyId(string data)
    {
        int id = Convert.ToInt32(data);
        tblProducto producto = db.tblProducto.Where(p => p.Id == id).SingleOrDefault();

        return Json(producto);
    }

This is the ajax call

    var id_producto = $('#id_producto option:selected').val();
$.ajax({
    url: '/Ventas/getProductbyId',
    type: 'post',
    data: { data:id_producto },
    success: function (data) {
        alert(data.cantidad);
    },
    error: function (data) {
        alert('La llamada (ajax)getProductbyId ha fallado');
    }
});

But I get the error alert.

Upvotes: 0

Views: 5611

Answers (1)

Dipin Mathew
Dipin Mathew

Reputation: 36

Try this : change the return format in controller

In Contoller :

[HttpPost]
public JsonResult getProductbyId(string data)
{
    int id = Convert.ToInt32(data);
    tblProducto producto = db.tblProducto.Where(p => p.Id == id).SingleOrDefault();
    return Json(producto, JsonRequestBehavior.AllowGet);
}

In Jquery (ajax call) :

var id_producto = $('#id_producto option:selected').val();
$.ajax({
       url: '/Ventas/getProductbyId',
       type: 'post',
       dataType: "JSON",
       data: { data:id_producto },
       processData: false,
       contentType: false,
       success: function (data) {
           alert(data);
       },
       error: function (data) {
           alert('La llamada (ajax)getProductbyId ha fallado');
       }
       });

Upvotes: 2

Related Questions