Working with Drop Down control in .Net Core MVC with steps

In previous articles we have learned about code first approach, Entity migration, crud operation in MVC .NET core, in this article i am going to demonstrate about work with drop down control in .NET Core MVC application with JQuery drop down binding.

I am going to use the same application which i have used in crud operation article. So lets start the implementation.

 


 

 

First we need to create the City and State models for that add below classes in ModelExample project.

 CityMaster.cs

 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel.DataAnnotations;  
 using System.ComponentModel.DataAnnotations.Schema;  
 using System.Text;  
 namespace ModelsExample  
 {  
   [Table("CityMaster")]  
   public class CityMaster  
   {  
     [Key]  
     [Column("Id")]  
     public int Id { get; set; }  
     [Column("Name")]  
     public string Name { get; set; }  
     [Column("StateMasterId")]  
     public int StateMasterId { get; set; }  
     public virtual StateMaster StateMaster { get; set; }  
 }  
 }  

  StateMaster.cs

 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel.DataAnnotations;  
 using System.ComponentModel.DataAnnotations.Schema;  
 using System.Text;  
 namespace ModelsExample  
 {  
   [Table("StateMaster")]  
   public class StateMaster  
   {  
     [Key]  
     [Column("Id")]  
     public int Id { get; set; }  
     [Column("Name")]  
     public string Name { get; set; }  
   }  
 }  

 To store the cityId and stateId in employee Table we need to add two properties in Employee model as below.

Employee.cs 

 using System;  
 using System.ComponentModel.DataAnnotations.Schema;  
 namespace ModelsExample  
 {  
   [Table("EmployeeMaster")]  
   public class Employee  
   {  
     [Column("Id")]  
     public int Id { get; set; }  
     [Column("Name")]  
     public string Name { get; set; }  
     [Column("Address")]  
     public string Address { get; set; }  
     [Column("CityId")]  
     public int CityId { get; set; }  
     [Column("StateId")]  
     public int StateId { get; set; }  
   }  
 }  

 

Now go to view >> Package manager Console and run below migration command to add the migration

  add-migration "AddedCityAndStateMaster"  

 after executing the above migration command below migration file will be created.

 using Microsoft.EntityFrameworkCore.Migrations;  
 namespace ModelsExample.Migrations  
 {  
   public partial class AddedCityAndStateMaster : Migration  
   {  
     protected override void Up(MigrationBuilder migrationBuilder)  
     {  
       migrationBuilder.AddColumn<int>(  
         name: "CityId",  
         table: "EmployeeMaster",  
         nullable: false,  
         defaultValue: 0);  
       migrationBuilder.AddColumn<int>(  
         name: "StateId",  
         table: "EmployeeMaster",  
         nullable: false,  
         defaultValue: 0);  
       migrationBuilder.CreateTable(  
         name: "StateMaster",  
         columns: table => new  
         {  
           Id = table.Column<int>(nullable: false)  
             .Annotation("SqlServer:Identity", "1, 1"),  
           Name = table.Column<string>(nullable: true)  
         },  
         constraints: table =>  
         {  
           table.PrimaryKey("PK_StateMaster", x => x.Id);  
         });  
       migrationBuilder.CreateTable(  
         name: "CityMaster",  
         columns: table => new  
         {  
           Id = table.Column<int>(nullable: false)  
             .Annotation("SqlServer:Identity", "1, 1"),  
           Name = table.Column<string>(nullable: true),           
           StateMasterId = table.Column<int>(nullable: true)  
         },  
         constraints: table =>  
         {  
           table.PrimaryKey("PK_CityMaster", x => x.Id);  
           table.ForeignKey(  
             name: "FK_CityMaster_StateMaster_StateMasterId",  
             column: x => x.StateMasterId,  
             principalTable: "StateMaster",  
             principalColumn: "Id",  
             onDelete: ReferentialAction.Restrict);  
         });  
       migrationBuilder.CreateIndex(  
         name: "IX_CityMaster_StateMasterId",  
         table: "CityMaster",  
         column: "StateMasterId");  
     }  
     protected override void Down(MigrationBuilder migrationBuilder)  
     {  
       migrationBuilder.DropTable(  
         name: "CityMaster");  
       migrationBuilder.DropTable(  
         name: "StateMaster");  
       migrationBuilder.DropColumn(  
         name: "CityId",  
         table: "EmployeeMaster");  
       migrationBuilder.DropColumn(  
         name: "StateId",  
         table: "EmployeeMaster");  
     }  
   }  
 }  

We have created models and migration  now we will create business class for MasterService.

Add Interface called IMasterService in businessService Project under Definition folder as below.

 using ModelsExample;  
 using System;  
 using System.Collections.Generic;  
 using System.Text;  
 namespace BusinessLayerExample.Definition  
 {  
   public interface IMasterService  
   {  
     List<StateMaster> GetStateMaster();  
     List<CityMaster> GetCityMaster(int StateId);  
   }  
 }  

 Add Class called MasterService in businessService Project under Implementation folder as below. 

 using BusinessLayerExample.Definition;  
 using ModelsExample;  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace BusinessLayerExample.Implementation  
 {  
   public class MasterService : IMasterService  
   {  
     private readonly SampleDbContext sampleDbObj;  
     public MasterService(SampleDbContext sampleDbObj)  
     {  
       this.sampleDbObj = sampleDbObj;  
     }  
     public List<CityMaster> GetCityMaster(int StateId)  
     {  
       return sampleDbObj.cityMasters.Where(obj => obj.StateId == StateId).ToList();  
     }  
     public List<StateMaster> GetStateMaster()  
     {  
       return sampleDbObj.stateMasters.ToList();  
     }  
   }  
 }  

 Now we need to add controller for MasterData in MVC project under Controller folder as below

 MasterDataController.cs

 using BusinessLayerExample.Definition;  
 using Microsoft.AspNetCore.Mvc;  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Threading.Tasks;  
 namespace Project_structiure_Example.Controllers  
 {  
   public class MasterDataController : Controller  
   {  
     private readonly IMasterService masterService;  
     public MasterDataController(IMasterService masterService)  
     {  
       this.masterService = masterService;  
     }  
     [HttpGet]  
     public IActionResult GetCity(int StateId)  
     {  
       var cityData= masterService.GetCityMaster(StateId);  
       return Json(cityData);  
     }  
   }  
 }  

 Now we need to modify the EmployeeController in order to fill the dropdown in view.

 using BusinessLayerExample.Definition;  
 using Microsoft.AspNetCore.Mvc;  
 using ModelsExample;  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Threading.Tasks;  
 namespace Project_structiure_Example.Controllers  
 {  
   public class EmployeeController : Controller  
   {  
     public readonly IEmployeeService employeeService;  
     public readonly IMasterService masterService;  
     public EmployeeController(IEmployeeService employeeServiceObj,IMasterService masterService)  
     {  
       employeeService = employeeServiceObj;  
       this.masterService = masterService;  
     }  
     public IActionResult Index()  
     {  
       var employees = employeeService.GetEmplyees();  
       return View(employees);  
     }  
     [HttpGet]  
     public IActionResult SaveEmployee()  
     {  
       ViewBag.StateMaster= masterService.GetStateMaster();  
       return View(new Employee());  
     }  
     [HttpPost]  
     public IActionResult SaveEmployee(Employee employee)  
     {  
      var result= employeeService.SaveEmployee(employee);  
       if(result)  
       {  
         return RedirectToAction("Index");  
       }  
       else  
       {  
         return View(employee);  
       }  
     }  
     [HttpGet]  
     public IActionResult UpdateEmployee(int id)  
     {  
       var employee = employeeService.GetEmplyees(id);  
       return View(employee);  
     }  
     [HttpPost]  
     public IActionResult UpdateEmployee(Employee employee)  
     {  
       var result = employeeService.UpdateEmployee(employee);  
       if (result)  
       {  
         return RedirectToAction("Index");  
       }  
       else  
       {  
         return View(employee);  
       }  
     }  
     [HttpGet]  
     public IActionResult DeleteEmployee(int id)  
     {  
       var employee = employeeService.GetEmplyees(id);  
       return View(employee);  
     }  
     [HttpPost]  
     public IActionResult DeleteEmployee(int id,Employee emp)  
     {  
       var result = employeeService.DeleteEmployee(id);  
       if (result)  
       {  
         return RedirectToAction("Index");  
       }  
       else  
       {  
         return View(emp);  
       }  
     }  
   }  
 }  

 

Now we need use the viewbag.StateMaster value in SaveEmployee view in DropDownListFor control.

SaveEmployee.chtml

 @*  
   For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860  
 *@  
 @using ModelsExample  
 @model Employee  
 @{  
 }  
 @section Scripts  
 {  
 <script type="text/javascript">  
   $(document).ready(function () {  
     $("#StateId").change(function () {  
       var stateId = $(this).val();  
       $.get("/MasterData/GetCity?StateId=" + stateId, function (data) {  
         var city = $("#CityId");  
         city.html('');  
         city.append($("<option/>", { value: "0", text: "Select" }));  
         if (data && data.length > 0) {  
           $.each(data, function (index, item) {  
             city.append($("<option/>", { value: item.id, text: item.name }));  
           });  
         }  
       });  
     });  
   });  
 </script>  
 }  
 @using (Html.BeginForm())  
 {  
   <h1>Enter Employee Details</h1>  
   <div>  
     @Html.LabelFor(model => model.Name)  
   </div>  
   <div>  
     @Html.TextBoxFor(model => model.Name)  
   </div>  
   <div>  
     @Html.LabelFor(model => model.Address)  
   </div>  
   <div>  
     @Html.TextBoxFor(model => model.Address)  
   </div>  
   <div>  
     @Html.LabelFor(model => model.StateId)  
   </div>  
   <div>  
     @Html.DropDownListFor(model => model.StateId, new SelectList(ViewBag.StateMaster, "Id", "Name", 0), "Select")  
   </div>  
   <div>  
     @Html.LabelFor(model => model.CityId)  
   </div>  
   <div>  
     @Html.DropDownListFor(model => model.CityId, new SelectList(Enumerable.Empty<SelectListItem>(), "Id", "Name", 0), "Select")  
   </div>  
   <hr />  
   <div>  
     <input type="submit" value="Submit" /> @Html.ActionLink("Back to employees", "Index")  
   </div>  
 }  

 In above code you can see that we have used dropdownlistfor for biding the statemaster. We have added section script for registering the state dropdown change event using Jquery.In the Change event we have called the Getcity api to fetch the cities based on the state dropdown selection.

We are done with our basic code now we can run the application and check the output.

drop down

 
save output

 

Comments

Popular posts from this blog

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

Implement Nlog in .Net core MVC application part 1

Angular User Session Timeout example step by step

Disable backspace key using Jquery

Devexpress Datebox date formatting in angular 6 with example