Follow us

Header Ads

Bind Dropdown List with Database in Asp.Net Core

Bind Dropdown List with Database in Asp.Net Core

Package

  • "Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0"
  •  "Microsoft.EntityFrameworkCore.Tools" Version="5.0.0"
  •  "Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" 

Controllers[Folder]

DropdownController.cs

using DropDown.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DropDown.Controllers
{
    public class DropdownController : Controller
    {
        private readonly ApplicationUser _auc;

        public DropdownController(ApplicationUser auc)
        {
            _auc = auc;
        }
        public IActionResult Index()
        {
            List<Country> cl = new List<Country>();
            cl = (from c in _auc.country select c).ToList();
            cl.Insert(0, new Country { Cid = 0, Cname = "--Select Country Name--" });
            ViewBag.message = cl;
            return View();
        }
    }
}

Models[Folder]

ApplicationUser.cs

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DropDown.Models
{
    public class ApplicationUser : DbContext
    {
        public ApplicationUser(DbContextOptions<ApplicationUser> options) : base(options)
        {

        }
        public DbSet<Country> country { get; set; }
    }
}

Country.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace DropDown.Models
{
    public class Country
    {
        [Key]
        public int Cid { get; set; }

        public string Cname { get; set; }
    }
}

Views[Folder]

Dropdown

Index.cshtml

@model DropDown.Models.Country
@{
    ViewData["Title"] = "Index";
}

<h1>Binding data into Dropdown list</h1>
<hr />
<select asp-for="Cid" asp-items="@(new SelectList(ViewBag.message,"Cid","Cname"))"></select>

appsettings.json

{
  "ConnectionStrings": {
    "Myconnection": "Data Source=CHETUIWK1689\\MSSQL2019;Initial Catalog=bindcountry;Integrated Security=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Startup.cs

using DropDown.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DropDown
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDbContext<ApplicationUser>(options => options.UseSqlServer(Configuration.GetConnectionString("Myconnection")));
            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Dropdown}/{action=Index}/{id?}");
            });
        }
    }
}


Post a Comment

0 Comments