【问题标题】:Can I exchange data between view and JsonResult method using ViewBag?我可以使用 ViewBag 在视图和 JsonResult 方法之间交换数据吗?
【发布时间】:2017-05-01 16:55:29
【问题描述】:

我正在为我的视图中的表实现排序,它通过调用 JsonResult 方法的 ajax 填充 这是我用于订购的标题链接:

<a style="cursor: pointer" onclick="getData('@Html.Raw(ViewBag.Sort == "asc" ? "desc" : "asc")')" id="sort">Title</a>

JsonResult 方法:

public JsonResult BooksData(string sort)
{
    ViewBag.Sort = ViewBag.Sort == "desc" ? "asc" : "desc";
    var books = new List<Book>();
    if (sort == "asc")
    {
        books = db.Books.Include(b => b.Author).OrderBy(b => b.Title).ToList();
        ViewBag.Sort = "desc";

    }
    else
    {
        books = db.Books.Include(b => b.Author).OrderByDescending(b => b.Title).ToList();
        ViewBag.Sort = "asc";

    }
    return Json(books, JsonRequestBehavior.AllowGet);
}

getsData 函数:

function getData(sort) {
            var srt = sort;
            $('#tbl>tbody').empty();

            $.ajax({
                type: 'GET',
                url: '/Book/BooksData?sort=' + srt,
                dataTtype: 'json',
                success: function (data) {
                    $.each(data, function (index, val) {
                        $('#tbl>tbody').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
                    });
                }
            });
        }

ViewBag.Sort 的值始终是asc

【问题讨论】:

  • ViewBag.Sort = sort == "desc" ? "asc" : "desc";
  • 第一行代码 - RHS ViewBag.Sort 的值始终为 null(您尚未设置)因此 LHS ViewBag.Sort 的值始终为 desc 和然后您的 else 块将其设置为 asc
  • 这听起来正确且合乎逻辑,但它仍然总是asc,不会改变!
  • 你为什么还要在onclick() 中再次反转它在你的视图中。有点难以理解你想在这里做什么
  • 我将此部分删除为getData('@ViewBag.Sort'),但是当我单击链接时,sort 的值变为空""

标签: ajax asp.net-mvc asp.net-mvc-routing jsonresult


【解决方案1】:

您的代码存在许多问题。首先@Html.Raw(ViewBag.Sort == ...) 是剃须刀代码,并在视图发送到客户端之前在服务器上进行评估,以便您生成

<a style="cursor: pointer" onclick="getData("asc")" id="sort">Title</a>

getData("desc") 取决于最初生成视图的 GET 方法中的 ViewBag.Sort 的值。没有你在哪里改变它,所以你的ajax调用总是为参数sort提交相同的值。

然后在BooksData() 方法中,您会遇到逻辑错误(尽管它们最终无关紧要)。因为您之前没有为ViewBag.Sort 设置值,所以

ViewBag.Sort = ViewBag.Sort == "desc" ? "asc" : "desc";

评估为

ViewBag.Sort = null == "desc" ? "asc" : "desc";

所以ViewBag.Sort 的值始终是"desc",然后您的else 块将重置为"asc"

但是您的方法返回的是JsonResult,而不是视图,因此ViewBag 的值会丢失,并且它的值永远不会返回给客户端。

将视图中的代码更改为

<a href="#" style="cursor: pointer" id="sort">Title</a>

并将ViewBag.Sort 的初始值分配给一个javascript 变量,以便每次单击链接时都可以切换它

var currentSort = '@Html.Raw(ViewBag.Sort)'
var url = '@Url.Action("BooksData", "Book")';
// handle the click event of the link
$('#sort').click(function() {
    // toggle the value
    currentSort  = currentSort == 'acs' ? 'desc' : 'asc';
    $('#tbl>tbody').empty();
    $.getJSON(url, { sort: currentSort }, function(data) {
        $.each(data, function (index, val) {
            .... // append table rows
        });
    });
});

然后是控制器方法

public JsonResult BooksData(string sort)
{
    if (sort == "asc")
    {
        var books = db.Books.Include(b => b.Author).OrderBy(b => b.Title); // no need for .ToList()`
        return Json(books, JsonRequestBehavior.AllowGet);
    }
    else
    {
        var books = db.Books.Include(b => b.Author).OrderByDescending(b => b.Title);
        return Json(books, JsonRequestBehavior.AllowGet);
    }
}

请注意,您可以通过简单地使用 javascript/jquery 重新排序表中的行来在客户端上进行“排序”,而无需额外开销调用服务器 - 请参阅 Invert table rows 示例,尽管表示在第一次生成视图后其他用户添加到数据库中的任何新记录都不会在视图中更新。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 1970-01-01
  • 2013-03-14
相关资源
最近更新 更多