如何在ASP.Net MVC中同时使用两个搜索下拉框?

时间:2018-01-16 18:00:10

标签: c# asp.net asp.net-mvc-4

我在MVC ASP.Net中有一个数据库项目。我希望用户能够使用两个下拉列表,并在同一屏幕上显示两组结果。

INDEX VIEW:

@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
    <p class="search">
        Team: @Html.DropDownList("playerTeam", "All")
        <input type="submit" value="Search" class="btn btn-default" />
    </p>
    <p class="search">
        Team: @Html.DropDownList("playerTeam2", "All")
    </p>
}

家庭控制器:

private PlayersDBEntities4 _db = new PlayersDBEntities4();
public ActionResult Index(string playerTeam, string playerTeam2)
    {
        var TeamList = new List<string>();
        var TeamQuery = from t in _db.PlayerInfoes
                        orderby t.Team
                        select t.Team.ToUpper();

        TeamList.AddRange(TeamQuery.Distinct());
        ViewBag.playerTeam = new SelectList(TeamList);

        var TeamList2 = new List<string>();
        var TeamQuery2 = from t in _db.PlayerInfoes
                        orderby t.Team
                        select t.Team.ToUpper();

        TeamList2.AddRange(TeamQuery2.Distinct());
        ViewBag.playerTeam2 = new SelectList(TeamList2);

var players = from p in _db.PlayerInfoes select p; //this is my database

        if (!String.IsNullOrEmpty(playerTeam))
        {
            players = players.Where(x => x.Team == playerTeam);
        }

        if (!String.IsNullOrEmpty(playerTeam2))
        {
            players = players.Where(x => x.Team == playerTeam2);
        }

return View(players.ToList());
    }

例如,如果我在第一个下拉框中选择了一个团队,而在第二个下拉框中选择了另一个团队,搜索结果将显示两个团队的玩家(此时每个框都单独工作以显示一个团队,但是一起使用我没有搜索结果。)

有谁知道如何使这个工作?

2 个答案:

答案 0 :(得分:1)

而不是使用

    if (!String.IsNullOrEmpty(playerTeam))
    {
        players = players.Where(x => x.Team == playerTeam);
    }

    if (!String.IsNullOrEmpty(playerTeam2))
    {
        players = players.Where(x => x.Team == playerTeam2);
    }

去寻找像

这样的东西
players = players.Where(x.Team == playerTeam || x.Team == playerTeam2)

并且确保它们都不会为空,除非你的团队没有名字,否则空字符串不会改变搜索结果。

答案 1 :(得分:0)

 public ActionResult Index(string searching)
{

 var items = new SelectList(new[] { "CSE", "ECE","EEE","IT","MBA" });
 ViewBag.DEP = items;
  ViewBag.Department = new SelectList(db.Sridevis, "Department", "DEP");

        if (!String.IsNullOrEmpty(searching))
        {
            faculty = faculty.Where( x.Department.StartsWith(search) );
        }
        return View(faculty.ToList());

}

HTML!
 <div>Department</div>
                                                            <div>
                                                                @Html.DropDownList("searching", (IEnumerable<SelectListItem>)ViewBag.DEP, "Select Department", new { @class = "form-control" })
                                                            </div>