我正在尝试为等级创建一个下拉列表,为类型创建一个下拉列表,以过滤包含等级,类型和名称的索引。
我的问题是我的下拉列表仅包含Microsoft.AspNetCore.MVC.Rendering
而不是实际值。
我已经注意到它显示Microsoft.AspNetCore.MVC.Rendering
的次数与它应在列表中显示的次数匹配。
我还想知道是否可以在等级过滤器获得值时将类型过滤器重置为null,因为您不能同时按等级和类型进行过滤(至少不是我知道的) ,因为索引只需要1个过滤器参数,我认为添加另一个过滤器参数会使它变得更加混乱)
这是我到目前为止所拥有的
模型
public class Lesson
{
public int LessonId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public int Rank { get; set; }
public string PhotoURL { get; set; }
public ICollection<PersonLesson> PersonLessons { get; set; }
public Lesson()
{
//for bridgtable, not important for this I assume
PersonLessons = new HashSet<PersonLesson>();
}
public Lesson(string name, string type, int rank) : this()
{
Name = name;
Type = type;
Rank = rank;
}
查看
@model IEnumerable<Taijitan.Models.Domain.Lesson>
@{
ViewData["Title"] = "Lessons";
}
<h2>@ViewData["Title"]</h2>
<div>
@Html.DropDownList("Type", ViewBag.Types, "Type", new { onchange = @"form.submit();" })
@Html.DropDownList("Rank", ViewBag.Ranks, "Rank", new { onchange = @"form.submit();" })
</div>
控制器
此代码包含很多代码,控制器和视图对我来说仍然有点模糊,因此我将其纳入全班学习,因为我不知道什么是重要的,什么不重要。
namespace Taijitan.Controllers
{
public class LessonController : Controller
{
private readonly ILessonRepository _LessonRepository;
public LessonController(ILessonRepository lessonRepository)
{
_LessonRepository = lessonRepository;
}
public IActionResult Index(string filter)
{
IEnumerable<Lesson> Lessons = null;
if (filter == null)
Lessons = _LessonRepository.GetAll();
else if (filter.All(c => char.IsDigit(c))) {
Lessons = _LessonRepository.GetByRank(int.Parse(filter));
}
else if (filter.All(c => char.IsLetter(c)))
{
Lessons = _LessonRepository.GetByType(filter);
}
ViewBag.Types = GetTypesAsSelectList();
ViewBag.Ranks = GetRanksAsSelectList();
return View(Lessen);
}
private SelectList GetTypesAsSelectList()
{
List<SelectListItem> TypesList = new List<SelectListItem>();
foreach (string type in _lessonRepository.GetTypes())
{
TypesList.Add(new SelectListItem { Text = type, Value = type});
}
return new SelectList(TypesList);
}
private SelectList GetRanksAsSelectList()
{
List<SelectListItem> RanksList = new List<SelectListItem>();
foreach (int rank in _LessonRepository.GetRanks())
{
RanksList.Add(new SelectListItem { Text = rank.ToString(), Value = rank.ToString()});
}
return new SelectList(RanksList);
}
}
回购
public class LessonRepository : ILessonRepository
{
private readonly DbSet<Lesson> _lessons;
private readonly ApplicationDbContext _dbContext;
public LessonRepository(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
_lessen = _dbContext.Lessons;
}
public IEnumerable<int> GetRanks()
{
return _lessen.Select(l => l.Rank).Distinct().ToList();
}
public IEnumerable<string> GetTypes()
{
return _lessons.Select(l => l.Type).Distinct().ToList();
}