.netentity-frameworkmodel-view-controlleref-code-firstdropdownlistfor

MVC filtering a table via a dropdown shows none


I want to filter a table using the Dropdown table. And I can select the modes I have in my DB by clicking the dropdown. The problem is whenever I press submit button with a selected dropdown nothing shows up. What I want to do is select a model from the dropdown(which I made, I guess) and then list all the games which have to play mode as the same I selected.

Index.cshtml

@model nproject.Models.TestViewModel
@using (Html.BeginForm("Index", "Test", FormMethod.Get))
{
    <label> Select a mode</label>
    @Html.DropDownListFor(f => f.SelectedMode, (List<SelectListItem>)ViewBag.dgr1, "Select")
    <input type="submit" value="Filter" />
}
<table>
    <tr>
        <th>games</th>
  
    </tr>
    @foreach (var item in Model.Data)
    {
        <tr>
            <td>@item.GameName)</td>

        </tr>
    }
</table>

Game.cs

    public int GameID{ get; set; }
    public string GameName{ get; set; }
    public Mode Modes{ get; set; } 

TestViewModel.cs

    public int Id { get; set; }
    public IEnumerable<Game> Data { set; get; }
    public string SelectedMode { set; get; }

Mode.cs

    public int ModeID{ get; set; }
    public string ModeName{ get; set; }

Controller

public class TestController: Controller
{
    private readonly GameContext db = new GameContext();
    // GET: Test
    public ActionResult Index(string selectedMode = "")
    {
        var vm = new TestViewModel();
       
       
        List<SelectListItem> deger1 = (from i in db.Mode.ToList()
                                       select new SelectListItem
                                       {
                                           Text = i.ModeName,
                                           Value = i.ModeID.ToString()
                                       }).ToList();
        ViewBag.dgr1 = deger1;

        var data = db.Game.ToList();
        if (!String.IsNullOrEmpty(selectedMode))
        {
            data = data.Where(x=>x.Modes.ModeName==selectedMode).ToList();
        }
        
        vm.Data = data.ToList();    
        return View(vm);
    }

Solution

  • I changed the line in controller from: data = data.Where(x=>x.Modes.ModeName==selectedMode).ToList(); to data = data.Where(x=>x.Modes.ModeID.ToString()==selectedMode).ToList(); nad problem is solved.