Search code examples
asp.net-mvc-4html-selecthtml.dropdownlistforviewbag

How create Dropdown list only using ViewBag in ASP.NET MVC 4?


Here I have a model class..

public class MyDrop
{
    public int id { get; set; }
    public string value { get; set; }
}

In my controller I use this code....

public ActionResult Index(){

    var GenreLst = new List<MyDrop>();

    MyDrop a = new MyDrop();
    a.id = 1;
    a.value = "hello";

    MyDrop b = new MyDrop();
    b.id = 2;
    b.value = "hello2";

    GenreLst.Add(a);
    GenreLst.Add(b);
    ViewBag.ShowDropDown = new SelectList(GenreLst); 


}

Then in my view I add this code...

@Html.DropDownList("ShowDropDown", "All")

After run the project.It show a dropdown list. But not showing correct values.

In the page source it likes this....

<select id="ShowDropDown " name="ShowDropDown "><option value="">All</option>
<option>DropDown.Models.MyDrop</option>
<option>DropDown.Models.MyDrop</option>
</select>

How do I solve this???

I was Expected like this.....

<select id="ShowDropDown " name="ShowDropDown "><option value="0">All</option>
<option value="1">hello</option>
<option value="2">hello2</option>
</select>

Please Help......


Solution

  • public ActionResult Index(){
    
        var GenreLst = new List<MyDrop>();
    
        MyDrop a = new MyDrop();
        a.id = 1;
        a.value = "hello";
    
        MyDrop b = new MyDrop();
        b.id = 2;
        b.value = "hello2";
    
        GenreLst.Add(a);
        GenreLst.Add(b);
        ViewBag.ShowDropDown = new SelectList(GenreLst, "id", "value"); 
    
    
    }
    

    In your View:

    @{
    SelectList list = ViewBag.ShowDropDown;
    }
    
    @Html.DropDownList("DROPDOWNID", list, "All")