【问题标题】:CRUD filtering/sorting doesnt work in asp.netCRUD 过滤/排序在 asp.net 中不起作用
【发布时间】:2017-08-27 13:55:03
【问题描述】:

我有这个需要排序/过滤的数据库。我当前的代码没有显示任何错误,但它什么也没做。

ApplicationUsersController.cs

// GET: ApplicationUsers
        public ActionResult Index(string sortOrder, string searchString)
        {
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.EmailSortParm = sortOrder == "Email" ? "email_desc" : "Email";
            var users = from c in db.Users
                           select c;
            if (!String.IsNullOrEmpty(searchString))
            {
                users = users.Where(c => c.Name.ToUpper().Contains(searchString.ToUpper())
                                       || c.Email.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "name_desc":
                    users = users.OrderByDescending(c => c.Name);
                    break;
                case "Email":
                    users = users.OrderBy(c => c.Email);
                    break;
                case "email_desc":
                    users = users.OrderByDescending(c => c.Email);
                    break;
                default:
                    users = users.OrderBy(c => c.Name);
                    break;
            }




            return View(db.Users.ToList());
        }

Index.cshtml

@using (Html.BeginForm())
{
    <p>
        Find by name: @Html.TextBox("SearchString")
        <input type="submit" value="Search" />
    </p>
}



<table class="table">
    <tr>
        <th>
            @Html.ActionLink("Email", "Index", new { sortOrder = ViewBag.EmailSortParm })
        </th>
        <th>
            @Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm })
        </th>

排序和过滤似乎都不起作用。排序时,地址栏变为

/ApplicationUsers?sortOrder=name_desc

但顺序根本没有改变。也许有人可以看到问题出在哪里?

编辑:

会不会是“var users = from c in db.Users select c;”字母“c”错了?我怎么能确定呢?

【问题讨论】:

    标签: c# asp.net sorting filtering crud


    【解决方案1】:

    变化:

    return View(db.Users.ToList());
    

    收件人:

    return View(users);
    

    :-)

    【讨论】:

    • 我不敢相信这有多么简单。谢谢。
    【解决方案2】:

    您需要将两个参数传递给操作Index:

    @Html.ActionLink("Email", "Index", new { sortOrder = ViewBag.EmailSortParm, searchString = null })
    

    【讨论】:

    • 感谢您的帮助,但是在输入此行后,我得到Cannot assign &lt;null&gt; to anonymous type property 在输入“”而不是“null”后,排序仍然不起作用。
    • 可以是'var users = from c in db.Users select c; '那个字母'c'是错的?我怎么能确定呢?
    猜你喜欢
    • 2013-11-08
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    相关资源
    最近更新 更多