Monday, April 19, 2021

MVC DropDownList Example

Create ASP.NET MVC Framework 4.7 based application.

Edit the App_Start/RouteConfig. Replace Home by Employee.

using System.Web.Mvc;
using System.Web.Routing;

namespace MVCDropdown1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}


Create Models/Employee.cs file.
namespace MVCDropdown1.Models
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public Sex Gender { get; set; }
        public int DepartmentID { get; set; }
    }

    public enum Sex
    {
        Male,
        Female
    }
}

Create Models/Department.cs file.
namespace MVCDropdown1.Models
{
    public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Create Models/EmployeeController.cs file.
using MVCDropdown1.Models;
using System.Collections.Generic;
using System.Web.Mvc;

namespace MVCDropdown1.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Index()
        {
            //Lets create list department for dropdownlist
            List ListDepartments = new List()
            {
                new Department() {Id = 1, Name="IT" },
                new Department() {Id = 2, Name="HR" },
                new Department() {Id = 3, Name="Payroll" },
            };

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


Create Views/Employee/Index.cshtml file.

@using MVCDropdown1.Models
@model MVCDropdown1.Models.Employee
<br />
<h5>Create dropdown control using Html.DropDownList and SelectList</h5>
@Html.DropDownList("EmployeeGender1",
                    new SelectList(Enum.GetValues(typeof(Sex))),
                    "Select Gender",
                    new { @class = "form-control" })
<br />
<h5>Create dropdown control using Html.DropDownListFor and SelectList</h5>
@Html.DropDownListFor(emp => emp.Gender,
                    new SelectList(Enum.GetValues(typeof(Sex))),
                    "Select Gender",
                    new { @class = "form-control" })
<br />
<h5>Create dropdown control using Html.DropDownList and SelectList</h5>
@Html.DropDownList("Department",
                    new SelectList(ViewBag.Departments, "Id", "Name"),
                    "Select Department",
                    new { @class = "form-control" })

Updated on 6 July 2023

No comments:

Post a Comment

Hot Topics