我想知道如何重构这样的一段代码。这是控制器中的一种方法,我正在通过ViewBag将2个SelectList传递给HTML。
public async Task<IActionResult> Index()
{
var teacherInfo = context.Teachers.OrderBy(x => x.Id);
IEnumerable<SelectListItem> selectList = from s in teacherInfo
select new SelectListItem
{
Value = s.Id.ToString(),
Text = s.FirstName + " " + s.LastName.ToString()
};
ViewBag.TeacherId = new SelectList(selectList, "Value", "Text");
var studentInfo = context.Students.OrderBy(x => x.Id);
IEnumerable<SelectListItem> selectListStudents = from s in studentInfo
select new SelectListItem
{
Value = s.Id.ToString(),
Text = s.FirstName + " " + s.LastName.ToString()
};
ViewBag.StudentId = new SelectList(selectListStudents, "Value", "Text");
return View();
}
我已经尝试过了,但是似乎我不能使用这样的泛型,因为T没有为Id和其他字段定义:
private async Task<IEnumerable<SelectListItem>> GetSelectListItem<T>(IOrderedQueryable<T> dbData)
{
IEnumerable<SelectListItem> selectList = from s in dbData
select new SelectListItem
{
Value = s.Id.ToString(),
Text = s.FirstName + " " + s.LastName.ToString()
};
return selectList;
}
任何帮助将不胜感激
答案 0 :(得分:0)
您需要将T约束到包含这些属性的接口上
internal interface IListItem
{
int Id { get; }
string FirstName { get; }
string LastName { get; }
}
然后让您的学生和老师实现此界面。
答案 1 :(得分:0)
您可以创建一个通用类,供学生和教师类继承。
public class BaseClassForSelectItems
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Students: BaseClassForSelectItems
{
}
public class Teachers: BaseClassForSelectItems
{
}
public async Task<IActionResult> Index()
{
var teacherInfo = context.Teachers.OrderBy(x => x.Id);
IEnumerable<SelectListItem> selectList = await GetSelectListItem(teacherInfo);
ViewBag.TeacherId = new SelectList(selectList, "Value", "Text");
var studentInfo = context.Students.OrderBy(x => x.Id);
IEnumerable<SelectListItem> selectListStudents = await GetSelectListItem(studentInfo);
ViewBag.StudentId = new SelectList(selectListStudents, "Value", "Text");
return View();
}
private async Task<IEnumerable<SelectListItem>> GetSelectListItem<T>(IOrderedQueryable<T> dbData) where T : BaseClassForSelectItems
{
IEnumerable<SelectListItem> selectList = from s in dbData
select new SelectListItem
{
Value = s.Id.ToString(),
Text = s.FirstName + " " + s.LastName.ToString()
};
return selectList;
}