HI WELCOME TO SIRIS

Part 35 - Setting an item selected when an asp.net mvc dropdownlist is loaded

Leave a Comment
we will discuss, how to set an item selected when an asp.net mvc dropdownlist options are loaded from a database table.

To have the "IT" department selected, when the departments are loaded from tblDepartment table, use the following overloaded constructor of "SelectList" class. Notice that we are passing a value of "1" for "selectedValue" parameter.
ViewBag.Departments = new SelectList(db.Departments, "Id""Name""1");

If you run the application at this point, "IT" department will be selected, when the dropdownlist is rendered. The downside of hard-coding the "selectedValue" in code is that, application code needs to be modified, if we want "HR" department to be selected instead of "IT". So every time there is a change in requirement, we need to change the application code.

Let's now discuss, the steps required to drive the selection of an item in the dropdownlist using a column in tblDepartment table.
Step 1: Add "IsSelected" bit column to tblDepartment table
ALTER TABLE tblDepartment
ADD IsSelected BIT

Step 2: At this point, this column will be null for all the rows in tblDepartment table. If we want IT department to be selected by default when the dropdownlist is loaded, set "IsSelected=1" for the "IT" department row.
Update tblDepartment Set IsSelected = 1 Where Id = 2

Step 3: Refresh ADO.NET Entity Data Model

Step 4: Finally, make the following changes to the "Index()" action method in "HomeController" class.
public ActionResult Index()
{
    SampleDBContext db = new SampleDBContext();
    List<SelectListItem> selectListItems = new List<SelectListItem>();

    foreach (Department department in db.Departments)
    {
        SelectListItem selectListItem = new SelectListItem
        {
            Text = department.Name,
            Value = department.Id.ToString(),
            Selected = department.IsSelected.HasValue ? department.IsSelected.Value : false
        };
        selectListItems.Add(selectListItem);
    }

    ViewBag.Departments = selectListItems;
    return View();
}

Run the application and notice that, "IT" department is selected, when the dropdownlist is loaded. 

If you now want "HR" department to be selected, instead of "IT", set "IsSelected=1" for "HR" department and "IsSelected=0" for "IT" department.
Update tblDepartment Set IsSelected = 1 Where Id = 2
Update tblDepartment Set IsSelected = 0 Where Id = 1

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.