Search code examples
c#asp.net-mvchtml-selecthtml.dropdownlistforviewbag

@Html.DropDownListFor Options with value and text without using ViewModels


Suppose I have a Simple table of group like in this picture,

I want to populate this as a dropdown having options value as GroupID and Name as text like shown here,

<select id="dropdown">
    <option value="1">superadmin</option>
    <option value="2">Support Desk</option>
    <option value="3" selected="selected">SSL I</option>
    <option value="4">SSL II Admin</option>
    <option value="5">SSL II</option>
    <option value="6">Client</option>
</select>

How Can I achieve this without using ViewModels and any complexity? Actually I want to do this only using ViewBag ? Is it possible ?

Note : This question is only for idea sharing purposes Please do not consider it as too broad.


Solution

  • Yes, I'm aware For sure it was possible,

    Approach 1 :

    In the view you can simply create a Dictionary<string, string> and those data in that Dictionary like here

        public ActionResult Index() {
                var dictionary = new Dictionary<string, string>();
                var allGroup = GetAllGroupNames(); //Query to get all data from table
    
                foreach(var ag in allGroup)
                {
                    dictionary.Add(ag.GroupId.ToString(), ag.Name);
    
                }
    
                ViewBag.selectGroupList = dictionary; // Add dictionary to ViewBag
    
                return View();
          }
    

    Then simply your DropDownListFor will looks like this,

     @Html.DropDownListFor(model => model.GroupId, new SelectList((Dictionary<string,string>)ViewBag.selectGroupList, "Key", "Value",new { @id="dropdown"}))
    

    Approach 2 :

     ViewBag.selectGroupList = new SelectList(GetAllGroupNames(), "GroupId", "Name");
    

    and in view

    @Html.DropDownListFor(model => model.GroupId, (SelectList)ViewBag.selectGroupList)
    

    Result:

    enter image description here

    Any better approaches rather than this will be appreciated