Domanda

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);
È stato utile?

Soluzione

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) 

Altri suggerimenti

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>";
        }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top