在SelectList MVC3中填充结果集
本文关键字:结果 填充 SelectList MVC3 | 更新日期: 2023-09-27 18:25:10
我在CourseRegisterModel
:中有以下SelectList声明
public class CourseRegisterModel
{
public StudentModel Student { get; set; }
public CourseModel Course { get; set; }
public IEnumerable<SelectListItem> CoursesList { get; set; }
public DateTime RegisterDate { get; set; }
}
在CourseController
中,我通过调用wcf web服务检索所有可用的课程:
public ViewResult Index()
{
ServiceCourseClient client = new ServiceCourseClient();
Course[] courses;
courses = client.GetAllCourses();
List<CourseModel> modelList = new List<CourseModel>();
foreach (var serviceCourse in courses)
{
CourseModel model = new CourseModel();
model.CId = serviceCourse.CId;
model.Code = serviceCourse.Code;
model.Name = serviceCourse.Name;
model.Fee = serviceCourse.Fee;
model.Seats = serviceCourse.Seats;
modelList.Add(model);
}
return View(modelList);//RegisterCourses.chtml
}
我需要在视图RegisterCourses.chtml
的下拉列表中填充这些课程。在上面的代码中,如何将所有记录放入selectlist?此外,我将如何在视图中使用该选择列表?
对于初学者,您的RegisterCourses.cshtml
需要使用:
@model <namespace>.CourseRegisterModel
然后,您的控制器代码将是:
public ViewResult Index()
{
ServiceCourseClient client = new ServiceCourseClient();
Course[] courses;
courses = client.GetAllCourses();
CourseRegisterModel model = new CourseRegisterModel();
//model = other model population here
model.CourseList = courses.Select(sl => new SelectListItem()
{ Text = sl.Name,
Value = sl.CId })
.ToList();
return View(model);
}
最后,回到您的视图(RegisterCourses.cs.html)-它应该包含:
@Html.DropDownListFor(m => m.Course.CId, Model.CourseList)
使用Html.DropDownList方法:http://msdn.microsoft.com/en-us/library/dd492738(v=vs.108).aspx
将下拉列表中所需的名称作为第一个参数,第二个参数在CourseList:中传递
@Html.DropDownList("课程列表",Model.CursesList)