I have a dropdownlist (also tried select list) and its items are coming from ViewBag. User will select an item and click button to list students in selected class.
It's ok but after postback dropdownlist's selected value is being reset.
I want the selected element in the list to remain unchanged.
(Please ignore if I made any inconsistencies while translating the feature names in the codes into English. There is no problem with the models and their features. All insert, update, delete operations are working. My only request is that the dropdownlist retains its selected value.)
View
@model IEnumerable<Proje.Models.Student>
<form asp-action="Index" method="post" >
@Html.DropDownList("groups", ViewBag.ListOfGroups,"Select...",new {@class="form-control"})
<button type="submit" class="btn btn-sm btn-danger">
List
</button>
</form>
Controller
public class StudentsController : Controller
{
private readonly ApplicationDbContext _context;
public StudentsController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
ViewBag.ListOfGroups = new SelectList(_context.Groups.OrderBy(k => k.Seviye).ThenBy(k => k.ShortName), "GroupId", "ShortName");
var applicationDbContext = _context.Students.Where(k => k.Group.GroupId == 1).Include(s => s.Group).OrderBy(k => k.Group.Level).ThenBy(k => k.Group.ShortName).ThenBy(k => k.Number);
return View(await applicationDbContext.ToListAsync());
}
[HttpPost]
public async Task<IActionResult> Index(string groups)
{
int Id = Convert.ToInt32(groups);
ViewBag.ListOfGroups = new SelectList(_context.Groups.OrderBy(k => k.Level).ThenBy(k => k.ShortName), "GroupId", "ShortName");
var applicationDbContext = _context.Students.Where(k => k.Group.GroupId==Id).Include(s => s.Group).OrderBy(k => k.Group.Level).ThenBy(k => k.Group.ShortName).ThenBy(k => k.Number);
return View(await applicationDbContext.ToListAsync());
}
}
I searched too much on StackOverflow and also on internet but couldn't find a solution for my problem or I didn't understand.
try this?
[HttpPost]
public async Task<IActionResult> Index(string groups)
{
int id = Convert.ToInt32(groups);
var students = await _context.Students
.Where(k => k.Group.GroupId == id)
.Include(s => s.Group)
.OrderBy(k => k.Group.Level)
.ThenBy(k => k.Group.ShortName)
.ThenBy(k => k.Number)
.ToListAsync();
selectedGroup = students.FirstOrDefault()?.Group;
var allGroups = _context.Groups
.OrderBy(k => k.Level)
.ThenBy(k => k.ShortName);
ViewBag.ListOfGroups = new SelectList(allGroups, "GroupId", "ShortName", selectedGroup);
return View(students);
}
The only difference is that we’re passing a group to SelectList()
. I’m using the students to get that group, so this will only work if there are any students in the selected group.