【问题标题】:Json results abc.json file instead of viewJson 结果 abc.json 文件而不是视图
【发布时间】:2017-08-01 07:40:23
【问题描述】:

我是第一次练习MVC asp.net,我正在尝试通过Jquery $.ajax 或$.getJSON 方法从Controller 获取产品列表到View,以下是控制器中的功能:

 public ActionResult List()
    {
      Dictionary<string, List<Product>> dict = new Dictionary<string, List<Product>> {{"pList", PList}};
      return Json(dict,JsonRequestBehavior.AllowGet);
    }

而ajax函数是:

 $(window).load(function () {
 $.ajax({
        url: '@Url.Action("List", "Product")',
        type: "GET",
        cache: false,
        success: function (data) {
            $("#div").append("<table><tr><td>ID</td><td>Name</td><td>Description</td><td>Price</td></tr>");
            data.pList.each(function () {
                $("#div").append("<tr>");
                $(this).each(function () {
                    $("#div").append("<td>" + $(this).Id() + "</td>");
                    $("#div").append("<td>" + $(this).Name() + "</td>");
                    $("#div").append("<td>" + $(this).Description() + "</td>");
                    $("#div").append("<td>" + $(this).Price() + "</td>");
                });
                $("#div").append("</tr>");
            });
            $("#div").append("</table>");
        }
    });
});

在加载 \Product\List 时,它会在浏览器上呈现 List.json 文件,而不是重定向到 \Product\List 并创建 ajax 成功函数中提供的动态表。我遵循了许多教程,表明这种方法是正确的。

【问题讨论】:

  • 调用视图的方法。
  • 先返回你的视图,然后使用对象触发AJAX调用(例如ActionLink或按钮)而不是直接使用$(window).load
  • 谢谢你,它成功了:)

标签: jquery asp.net json ajax asp.net-mvc


【解决方案1】:

加载(函数(){ $.ajax({ url: '/列表/产品', 类型:“获取”, 缓存:假, 成功:函数(数据){ $("#div").append("IDNameDescriptionPrice"); data.pList.each(函数(){ $("#div").append(""); $(this).each(function () { $("#div").append("" + $(this).Id() + ""); $("#div").append("" + $(this).Name() + ""); $("#div").append("" + $(this).Description() + ""); $("#div").append("" + $(this).Price() + ""); }); $("#div").append(""); }); $("#div").append(""); } }); });`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多