Search code examples
c#asp.net-mvcdropdownlistfor

ASP.NET MVC - How to transfer the selected item from DropDownListFor to the Controller


I'm making a DropDownListFor and pulling its items with the model.

But I cannot transfer the selected item from DropDownListFor to the controller.

Index.cshtml:

@using (Html.BeginForm("Index", "StudentTable", FormMethod.Get))
{
    <p>
        <p>Class:</p>
        <div class="form-group">
            <select class="form-control" id="SelectedId">
                @foreach (var item in Model)
                {

                    <option value="@item.ClassId">@item.Class.ClassName</option>
                }
            </select>
        </div>
        <input type="submit" value="Ara">
    </p>
}

Controller:

StudentDatabaseContext db = new StudentDatabaseContext();
public ActionResult Index(string SelectedId)
{
    var studentList = db.StudentTables.Include(x => x.Class).ToList();
    var degerler = from d in db.StudentTables select d;
    if (!string.IsNullOrEmpty(SelectedId))
    {
        degerler = degerler.Where(m => m.ClassId.ToString().Contains(SelectedId));
    }
    return View(degerler.ToList());
}

What is the problem? How can I solve it? Thanks for the help.


Solution

  • Provide the name attribute to the select element, so the value will be passed as SelectedId to the controller.

    <select class="form-control" id="SelectedId" name="SelectedId">
        ...
    </select>
    

    enter image description here