简体   繁体   中英

Strongly-Typed Model: How do I handle dropdown lists?

I've created a partial view which represents the admin side of a blog. In my model I've created a property and method shown below.

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;
        }
    }   
}

View:

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

Now the whole goal was to use GetHeaderImages() to build the list, then store the selected value in the HeaderImage property and eventually save that to the DB. Right now, the select list renders but instead of displaying text values, it displays the entire System.Web.MVC.SelectListItem object.

I guess the question I'm asking is: what's the ideal way for building a select list in a model (from a datasource), then populating another property in that model with the selected value?

You are doing it right, but you have to tell the dropdown which field to display as text and witch to have as a value.

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

Don't create a select list. It just expects the items:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM