Home > Software design >  Populating the dropdown from the controller method
Populating the dropdown from the controller method

Time:11-13

I am trying to create a dropdown in my index page and populate it with values from the Controller method. I created a method in the controller get the values for a dropdown that needs to be added in the index() page

    private SortedSet<string> getRooms(DbSet<RmRoom> rmRooms)
    {
        var roomNameSet = new SortedSet<string>();
        foreach (var item in rmRooms)
        {
            roomNameSet.Add(item.Name);
        }
        return roomNameSet;
    }

Now on the index page I am not sure how to call this method to populate the dropdown

    <select id="dropdownRoom">
        <option value="0">Select Room</option>
       //here how to call the controller method    
    </select>

Most of the forums talks about using the ViewData/ ViewBag. But I wanted to check if we can directly call the controller action to populate the dropdown list

CodePudding user response:

Your getRooms is a private method,so view cannot call it directly,unless you change it to a public method,but use ViewData/ ViewBag to pass data to view in Index action is more safely,so that others will also cannot call getRooms directly.

Here is a demo with ViewData:

public IActionResult Index()
        {
            ...
            ViewData["RoomList"]=getRooms(rmRooms);
            return View();
        }

View:

<select id="dropdownRoom">
    <option value="0">Select Room</option>
    @foreach (var item in ViewData["RoomList"] as IEnumerable<string>)
    {
        <option value=@item>@item</option>
    }
</select>
  • Related