【问题标题】:How to return a model to ajax call in MVC 5如何在 MVC 5 中将模型返回给 ajax 调用
【发布时间】:2020-01-29 07:47:14
【问题描述】:

我的目标是使用另一个表中的数据限制某些输入,因此我尝试通过 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');
    }
});

但我收到错误警报。

【问题讨论】:

    标签: asp.net-mvc-5 asp.net-ajax


    【解决方案1】:

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

    在控制器中:

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

    【讨论】:

      猜你喜欢
      • 2016-01-08
      • 1970-01-01
      • 2016-11-22
      • 2020-04-18
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      相关资源
      最近更新 更多