문제

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>";
        }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top