【问题标题】:C# MVC fires Success before "return Json"C# MVC 在“返回 Json”之前触发 Success
【发布时间】:2017-01-01 03:27:53
【问题描述】:

我有一个带有脚本(包括在下面)的视图,该脚本会在下拉列表更改时触发,并且事件处理程序应该填充两个文本输入的值。从控制器接收值。

我遇到的问题是,一旦itemstatus 列表被填充,控制器就会返回视图,并且没有值被传递回 AJAX 函数。

如果我删除 itemstatus 列表代码并手动分配值,如下所示:

var result = new { Quantity = "123", Price = "555"};

然后就可以了。

我还尝试了其他方法在控制器中获取数据,但结果相同。你有什么想法我做错了什么以及为什么控制器在“返回 Json”之前返回视图

<script type="text/javascript">

$(document).ready(function() {
    //Dropdownlist Selectedchange event
    $("#dropdown1").change(function ()
    {
        $("#txtQuantity").empty();
        $("#txtPrice").empty();
        $.ajax(
        {
            type: 'POST',
            url: '@Url.Action("GetValues")', 
            dataType: 'json',
            data: { id: $("#dropdown1").val() },
            success: function(data) 
            {
                $("#txtQuantity").val(data.Quantity);
                $("#txtPrice").val(data.Price);
            }
        })
    })
});

控制器:

 public JsonResult GetValues(int id)
    {

        List<Item> itemstatus =
           (from pd in db.Item

            where (pd.itemID == id) 
            select new Item()
            {
                itemPrice = pd.itemPrice,
                itemQuantity = pd.itemQuantity
            }).ToList();

         ...
         more code where i select what i need as a result i have two strings named itemquantity and itemprice
         ...

        var result = new { Quantity= itemquantity, Price = itemprice };
        return Json(result, JsonRequestBehavior.AllowGet);

}

【问题讨论】:

  • 对不起!这是什么意思 ? 一旦填充了 itemstatus 列表,控制器就会返回视图,并且没有值被传递回 ajax 函数 ?
  • 抱歉,不够清楚。因此,只要执行此行: List itemstatus = (from pd in db.Item where (pd.itemID == id) select new Item() { itemPrice = pd.itemPrice, itemQuantity = pd.itemQuantity } ).ToList();控制器返回视图。
  • 这是我不明白的部分控制器返回查看?你怎么知道 ?该方法是通过当前视图中的 ajax 调用执行的。因此,在执行该代码时,您仍然可以在浏览器中看到当前视图。那么控制器返回视图是什么意思?哪个视图?您已经看到了一个视图。
  • 另外,函数(数据)似乎根本没有启动
  • 您的 ajax 调用是否返回 200 响应?检查您的浏览器开发工具->网络选项卡并查看 ajax 调用的响应

标签: c# json ajax asp.net-mvc


【解决方案1】:

因为您正在发送一个列表,其数据值可以使用

success: function(data) 
        {
            $("#txtQuantity").val(data[0].Quantity);
            $("#txtPrice").val(data[0].Price);
        }

【讨论】:

    猜你喜欢
    • 2014-11-05
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多