Follow us

Header Ads

BindDropDownWithDatabase

BindDropDownWithDatabase

Install 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]

CoursesController.cs

using ManualOperations.Data;

using ManualOperations.Models;

using Microsoft.AspNetCore.Mvc;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;


namespace ManualOperations.Controllers

{

    public class CoursesController : Controller

    {

        private readonly DataContext _context;

        public CoursesController(DataContext context)

        {

            _context = context;

        }

        //Get Section of Course Model

        [HttpGet]

        public IActionResult Index()

        {

            var courses = _context.Courses.ToList();

            return View();

        }

        [HttpGet]

        public IActionResult Create()

        {

            return View();

        }

        [HttpGet]

        public IActionResult Detail(int id)

        {

            var courses = _context.Courses.Where(x => x.Id == id).FirstOrDefault();//Lamda Expression

            return View();

        }

        [HttpGet]

        public IActionResult Edit(int id)

        {

            var courses = _context.Courses.Where(x => x.Id == id).FirstOrDefault();//Lamda Expression

            return View();

        }

        //Post Section of Course Model

        [HttpPost]

        public IActionResult Create(Course model)

        {

            return View();

        }


    }

}

TextController.cs

using ManualOperations.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BindDropDownWithDatabase.Controllers
{
    public class TextController : Controller
    {
        private readonly DataContext _context;
        public TextController(DataContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
            ViewBag.courses = new SelectList(_context.Courses, "Id", "Title");
            return View();
        }
    }
}

Data[Folder]

DataContext.cs

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

namespace ManualOperations.Data
{
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions<DataContext>options):base(options)
        {

        }
        public DbSet<Student> Students { get; set; }
        public DbSet<Course> Courses { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>().ToTable("Student_Table");
            modelBuilder.Entity<StudentCourse>().ToTable("StudentCourse_Table");
            modelBuilder.Entity<Course>().ToTable("Course_Table");
        }
    }
}

Models[Folder]

ApplicationUser.cs


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

namespace BindDropDownWithDatabase.Models
{
    public class ApplicationUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public Gender Gender { get; set; }
    }
    //enumaration
    public enum Gender
    {
        Male,
        Female,
        Others
    }
}

Course.cs

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

namespace ManualOperations.Models
{
    public class Course
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Code { get; set; }
        public ICollection<StudentCourse> Enrollment { get; set; }
    }
}

Student.cs


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

namespace ManualOperations.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime Enrolled { get; set; }
        public ICollection<StudentCourse> Enrollment { get; set; }
    }
}

StudentCourse.cs


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

namespace ManualOperations.Models
{
    public class StudentCourse
    {
        public int Id { get; set; }
        public int StudentId { get; set; }
        public int CourseId { get; set; }

        public Student Student { get; set; }
        public Course Course { get; set; }

    }
}

ViewModels[Folder]

ApplicationUserModels.cs


using BindDropDownWithDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BindDropDownWithDatabase.ViewModels
{
    public class ApplicationUserModels
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public Gender Gender { get; set; }
    }
    public enum Gendr
    {
        Male,
        Female,
        Others,
    }
}

Views[Folder]


[Text->Index]

@model BindDropDownWithDatabase.Models.ApplicationUser

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<h4>ApplicationUser</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Index">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="FirstName" class="control-label"></label>
                <input asp-for="FirstName" class="form-control" />
                <span asp-validation-for="FirstName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="LastName" class="control-label"></label>
                <input asp-for="LastName" class="form-control" />
                <span asp-validation-for="LastName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Address" class="control-label"></label>
                <input asp-for="Address" class="form-control" />
                <span asp-validation-for="Address" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Gender" class="control-label"></label>
               <select  asp-items="ViewBag.courses">
                   <option value="">Select Gender</option>
               </select>
                <span asp-validation-for="Gender" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

appsettings.json


{

  "ConnectionStrings": {
    "DefaultConnection": "Server=CHETUIWK0541\\SQL2019NEW;Database=GST;Trusted_Connection=True;MultipleActiveResultSets=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Startup.cs


using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
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 BindDropDownWithDatabase
{
    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();
        }

        // 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=Home}/{action=Index}/{id?}");
            });
        }
    }
}




Post a Comment

0 Comments