简体   繁体   中英

Appending two default value to a dropdownlistfor MVC 4

How do I append two default value to a dropdownlistfor

 List<SelectListItem> items = new List<SelectListItem>();
        sStreet = "<option value=0>Select</option>";
        sStreet = "<option value=1>Other</option>";
        foreach (System.Data.DataRow dr in ViewBag.tname.Rows)
        {
            txt = @dr["StreetName"].ToString();
            valu = @dr["id"].ToString();
            sStreet += "<option value=" + valu + ">" + txt + "</option>";
        }
        return Content(sStreet);

I would do it like this

List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem() { Text = "Select", Value = "0" });
items.Add(new SelectListItem() { Text = "Other", Value = "1" });
foreach (System.Data.DataRow dr in ViewBag.tname.Rows)
{
    items.Add(new SelectListItem() { Text = dr["StreetName"].ToString(), Value = dr["id"].ToString() });
}
//then pass items to the view through your model

on your view you should then set up the dropdownlistfor like this

@Html.DropDownListFor(x => x.SelectedValue, Model.items) 

I fixed it by adding another option after the select option

 items = "<option value=0>Select</option><option value=0>Other</option>";          
        foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
        {
            txt = @dr["StreetName"].ToString();
            valu = @dr["id"].ToString();
            items += "<option value=" + valu + ">" + txt + "</option>";
        }

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