将两个默认值附加到MVC 4的下拉列表中

时间:2014-02-12 14:31:44

标签: c# visual-studio asp.net-mvc-4 razor-2

如何将两个默认值附加到下拉列表

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

2 个答案:

答案 0 :(得分:0)

我会这样做

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

在您的视图中,您应该像这样设置下拉列表

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

答案 1 :(得分:0)

我通过在选择选项

之后添加另一个选项来修复它
 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>";
        }