Reputation: 493
Say I have
public async Task<IActionResult> View()
{
ViewData["Employee"] = new SelectList(_userManager.Users.ToList(), "Id", "FullName");
List<ScreenshotItem> screenshotItems = await _context.ScreenshotItems.ToListAsync();
ScreenshotViewModel model = new ScreenshotViewModel();
model.ScreenshotItems = screenshotItems;
return View(model);
}
And then I simply display the images:
@Html.DropDownList("Id", (SelectList) ViewBag.Employee, new {onchange = "View()"}))
@foreach (var ss in Model.ScreenshotItems)
{
<div>
<img src="@ss.Path" alt="@ss.Path"/>
<label>@ss.EmployeeId</label>
</div>
}
What I'm trying to accomplish is I want to filter the list using a DropDownList, so on every change of the dropdownlist I want the list to be updated. Is this possible?
Upvotes: 0
Views: 126
Reputation: 2543
According to your ViewModel, in your View you'll have some thing like this:
@using Project.Path.To.Your.ScreenshotViewModel
@model ScreenshotViewModel
@{
List<SelectListItem> listItems = new List<SelectListItem>();
Model.ScreenshotItems.ToList().ForEach(x => {
listItems.Add(new SelectListItem { Text = x.EmployeeName, Value = x.EmployeeId.ToString() });
});
@Html.DropDownList("selectList", listItems, new { @onchange = "foo()" })
<ul id="UList">
@foreach (var i in Model.ScreenshotItems)
{
<li tagValue="@i.EmployeeId">
<img src="@i.Path" alt="@i.Path"/>
<label>@i.EmployeeName</label>
</li>
}
</ul>
}
and, at the bottom of that view, you can add or bundle this javascript code:
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function foo() {
var empName = $("select#selectList :selected").text();
var empID = $("select#selectList :selected").val();
//alert(empName);
$('ul#UList').find('li').each(function (index, el) {
//alert($(this).attr('tagValue'));
$(this).attr('tagValue') == empID ? $(this).removeClass('hidden') : $(this).addClass('hidden');
});
}
</script>
You will customize this code wherever needed. For instance, It's a better idea to use department ID as for 'tagValue' attribute, so that you can filter all Employees belonging to a specific department, by selecting the department name from the drop down. In addition, you may change <ul><li>
tags to nested <div>
s with same class attribute. Don't forget to include bootstrap.
Hope this helps.
Upvotes: 1