0

如何让模型中的值与下拉列表中的选定值匹配?

我想做的是让下拉列表反映模型的属性值。我只能在所有下拉列表中显示相同的值。我一直在尝试这样做:

@Html.DropDownList("searchString", Model.Enrollments.FirstOrDefault().WeekDays.Select(s => 
   new SelectListItem { Text = s.ToString(), Value = s.ToString(), 
   Selected = s.ToString().Equals(Model.Enrollments.FirstOrDefault().classDays) }))

但没有运气。

我的注册模型片段:

    public string[] weekDays = new string[6] { "Day", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };

    public string[] WeekDays

    {

        get { return weekDays; }

    }

我的观点是:@model SchoolIn.Models.Student 但我想插入另一个模型 Model.Enrollments 并缩小下拉列表项。

  <table>
     <tr>
              @{
     int cnt = 0;
        List<SchoolIn.ViewModels.EnrolledCourseData> courses = ViewBag.Courses;

        foreach (var course in courses)
        {
            if (cnt++ % 4 == 0)
            {

                       @:  </tr> <tr>


             }
                       @: <td >  
                      <br /><br /><br />
                    <input type="checkbox"  
                           name="selectedCourses"  
                           value="@course.CourseID"  
                           @(Html.Raw(course.Assigned ? "checked=\"checked\"" : "")))

   />  


                    @*course.CourseID @:  @course.Title*@
                    @course.Title<br />  <br />

      if (Model.Enrollments != null)
      {



       @Html.DropDownList("searchString", Model.Enrollments.FirstOrDefault().WeekDays.Select(s => new SelectListItem { Text = s.ToString(), Value = s.ToString(), Selected = s.ToString().Equals(Model.Enrollments.FirstOrDefault().classDays) })) 

     }




                                 @:</td> 



       }
                                @:</tr> 

 }

          </table>
4

1 回答 1

0
@Html.DropDownListFor( x => x.courseId, new SelectList(LookupUtils.AvailableCourcesList(), "Value", "Text", Model.courseId))

LookupUtils 是一个静态类有:

public static List<SelectListItem> AvailableCourcesList()
{
    var dataContext = new YourDataContext(  );
    var data = dataContext.GetCourcesFn().ToList();

    var result = ( from res in data
                   select new SelectListItem()
                              {
                                  Text = res.courseName,
                                  Value = res.courseId.ToString()
                              } ).ToList();

    return result;
}
于 2012-10-01T05:19:02.663 回答