1

我在以下 SelectList 声明CourseRegisterModel

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
    }

我需要在 view 的下拉列表中填充这些课程RegisterCourses.chtml。如何在上面的代码中将所有记录放在选择列表中?另外,我将如何在视图中使用该选择列表?

4

2 回答 2

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)
于 2013-07-28T16:30:58.700 回答
0

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

传入下拉列表的所需名称作为第一个参数,作为第二个参数传入您的 CourseList:

@Html.DropDownList("CoursesList", Model.CoursesList)

于 2013-07-28T15:37:41.647 回答