强类型模型:如何处理下拉列表?

强类型模型:如何处理下拉列表?

问题描述:

我创建了一个代表博客管理员端的部分视图。在我的模型中,我创建了如下所示的属性和方法。强类型模型:如何处理下拉列表?

public int HeaderImage { get; set; } 

public IEnumerable<SelectListItem> GetHeaderImages() 
{ 
    List<SelectListItem> d = new List<SelectListItem>(); 

    using (SqlConnection connection = new SqlConnection(
     ConfigurationManager.ConnectionStrings["KineticBombardment"].ToString())) 
    { 
     using (SqlCommand cmd = new SqlCommand("select id, imagepath from blogheaderimages", 
      connection)) 
     { 
      cmd.Parameters.Clear(); 
      connection.Open(); 
      cmd.ExecuteNonQuery(); 

      using (SqlDataReader reader = cmd.ExecuteReader()) 
      { 
       while(reader.Read()) 
       { 
        SelectListItem item = new SelectListItem(); 
        item.Text = reader["id"].ToString(); 
        item.Value = reader["imagepath"].ToString(); 

        d.Add(item); 
       } 
      } 

      return d; 
     } 
    } 
} 

查看:

<div class="input"> 
    @Html.DropDownListFor(x => x.HeaderImage, 
     new SelectList(Model.HeaderImageList)) 
</div> 

现在整个目标是使用GetHeaderImages()建立列表,然后选择的值存储在HeaderImage财产,最终是保存到数据库中。现在,选择列表呈现,但不是显示文本值,而是显示整个System.Web.MVC.SelectListItem对象。

我想我问的问题是:什么是在模型中建立选择列表(从数据源),然后用选定的值填充该模型中的另一个属性的理想方式是什么?

+0

请投票,如果答案帮助你 – mattematico 2012-08-07 05:44:08

你做得对,但你必须告诉下拉字段显示为文本和女巫作为一个值。

<div class="input"> 
     @Html.DropDownListFor(x => x.HeaderImage, 
      new SelectList(Model.HeaderImageList, "Value", "Text")) 
    </div> 

不要创建选择列表。它只是期望的项目:

<div class="input"> 
    @Html.DropDownListFor(x => x.HeaderImage, Model.GetHeaderImages()) 
</div>