How To Declare DropDownList Using ViewData In MVC

In this article i will explain you how to declare dropdownlist different ways in mvc
we are declaring dropdownlist  statically
Step1:-Using ViewData
    @using(Html.BeginForm())
    {
        List<SelectListItem> objListItem = new List<SelectListItem>();
        objListItem.Add(new SelectListItem() { Text = "Option1", Value = "opt1" });
        objListItem.Add(new SelectListItem() { Text = "Option2", Value = "otp2" });
        objListItem.Add(new SelectListItem() { Text = "Option3", Value = "opt3" });
        ViewData["DropDownList1"] = objListItem;
        @Html.DropDownList("DropDownList1")
    }
Second Way:-Using ViewData
    @using (Html.BeginForm())
    {
        List<SelectListItem> objSelectItem = new List<SelectListItem>()
        {
            new SelectListItem{Text="Option1",Value="opt1"},
            new SelectListItem{Text="Option2",Value="opt2"},
            new SelectListItem{Text="Option3",Value="opt3"},
            new SelectListItem{Text="Option4",Value="opt4"}
        };
       ViewData["DropDownList1"] = objSelectItem;
        @Html.DropDownList("DropDownList1","Select Option")
    }

If we not specify ViewData then we will get an exception


No comments:

Post a Comment