如何 return 模型 ajax 在 MVC 5 中调用

How to return a model to ajax call in MVC 5

我的目标是使用来自另一个 table 的数据限制某些输入,因此我尝试通过 ajax 调用来实现。

这是控制器:

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

        return Json(producto);
    }

这是ajax调用

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

但我收到错误警报。

试试这个:更改控制器中的 return 格式

在控制器中:

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

在Jquery(ajax调用):

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