在SelectList MVC3中填充结果集

时间:2013-07-28 15:31:45

标签: c# asp.net-mvc-3 selectlistitem

我在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的下拉列表中填充这些课程。如何在上面的代码中将所有记录放入选择列表中?我如何在视图上使用该选择列表?

2 个答案:

答案 0 :(得分:1)

对于初学者,您的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.cshtml) - 它应该包含:

@Html.DropDownListFor(m => m.Course.CId, Model.CourseList)

答案 1 :(得分:0)

使用Html.DropDownList方法:http://msdn.microsoft.com/en-us/library/dd492738(v=vs.108).aspx

将下拉列表的所需名称作为第一个参数传递,作为第二个参数传递到CourseList中:

@ Html.DropDownList(“CoursesList”,Model.CoursesList)