Search code examples
c#visual-studioasp.net-mvc-4razor-2

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

Solution

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