Skip to content
Advertisement

To add dropdownlist using a secondary table column values

I have to add a dropdownlist to my existing project “moviesite”, i have a primary table moviestable for adding, edit delete movies. now added a new table Genre to add movieGenre. second table consist of two column , “GenreId set as primarykey and identity , second column is name( consist of genre types like Action, drama ,comdey etc.) and added a column GenreRefId to primary table and set as Foreign-key. now i want to access the secondary table’s column for a dropdown in the main project. so i created a new model class “GenreClass.cs” and added it to dbcontext. now i am stucked with how to implement it in model,controller and index.

NewmovieClass.cs 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Moviesite.Enums;
using System.ComponentModel.DataAnnotations.Schema;

namespace Moviesite.Models
{
    public class NewmovieClass
    {
        [Key]

    
        public int Movieid { get; set; }

        [Required]
        public string Movietitle { get; set; }

        [Required]
        public string Description { get; set; }

        [Required]
        public string Storyline { get; set; }

        public int Year { get; set; }

        public DateTime Releasedate { get; set; }

        public int Runtime { get; set; }
        [Column(TypeName="nvarchar(50)")]
        public Mvetypenum MovieType { get; set; }



        public int GenreRefId { get; set; }

        [ForeignKey("GenreRefId")]

        public GenreClass Genre { get; set; }

    }
}






GenreClass.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Moviesite.Enums;
using System.ComponentModel.DataAnnotations.Schema;


namespace Moviesite.Models
{
    public class GenreClass
    {
       [Key]
        public int GenreId { get; set; }
        
        public string Name { get; set; }

        public ICollection<NewmovieClass> newmovieClasses { get; set; }
     
    }
}









MveController.cs


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

namespace Moviesite.Controllers
{
    public class MveController : Controller
    {
        private readonly ApplicationDbContext _db;

        
        public MveController(ApplicationDbContext db)
        {
            _db = db;
        }
        public IActionResult Index()
        {

            var displaydata = _db.Moviestable.ToList();
            return View(displaydata);


            
        }

        [HttpGet]

        public async Task<IActionResult> Index (String Mvesearch)

        {
            ViewData["Getmoviedetails"] = Mvesearch;

            var mvequery = from x in _db.Moviestable select x;

            if (!string.IsNullOrEmpty(Mvesearch))

            {
                mvequery = mvequery.Where(x => x.Movietitle.Contains(Mvesearch) || x.Description.Contains(Mvesearch));
            }

            return View(await mvequery.AsNoTracking().ToListAsync());

        }
        public IActionResult Create()

        {
            return View();


        }
        [HttpPost]
        public async Task<IActionResult> Create([Bind("Movieid,Movietitle,Description,Storyline,Year,Releasedate,Runtime,MovieType")] NewmovieClass nmc)
        {

            if (ModelState.IsValid)
          {
                _db.Add(nmc);
                await _db.SaveChangesAsync();
                return RedirectToAction("Index");

            }
            return View(nmc);
        }

        public async Task< IActionResult> Edit(int? id)
        {
            if(id==null)
            {
                return RedirectToAction("Index");
            }
            var getmvedetails = await _db.Moviestable.FindAsync(id);
            return View(getmvedetails);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(NewmovieClass mc)
        {
            if (ModelState.IsValid)
            {
                _db.Update(mc);

                await _db.SaveChangesAsync();

                return RedirectToAction("Index");


            }
            return View(mc);

        }

        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("Index");
            }
            var getmvedetails = await _db.Moviestable.FindAsync(id);
            return View(getmvedetails);
        }

        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("Index");
            }
            var getmvedetails = await _db.Moviestable.FindAsync(id);
            return View(getmvedetails);
        }

        [HttpPost]

        public async Task<IActionResult> Delete(int id)
        {
            
            var getmvedetails = await _db.Moviestable.FindAsync(id);

            _db.Moviestable.Remove(getmvedetails);

            await _db.SaveChangesAsync();

            return RedirectToAction("Index");
        }

       
        
           

           
           
       
        

       
    }
}






AppDbcontext



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


namespace Moviesite.Models
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {

        }

        public DbSet<NewmovieClass> Moviestable { get; set; }

      public DbSet<GenreClass> Genre { get; set; }


    }

    }



Advertisement

Answer

First-step fetch and List of Genres and set in a viewbag

public IActionResult Create()

        {
           viewbag.Genres=new SelectList(_db.Genre,"Name","GenreId");
            return View();


        }

second-step : bind into dropdown html

 <select asp-for="GenreRefId" asp-items="viewbag.Genres"></select>

third-step : Add GenreRefId in Post Methode

    [HttpPost]
    public async Task<IActionResult> Create([Bind("Movieid,Movietitle,Description,Storyline,Year,Releasedate,Runtime,MovieType,GenreRefId")] NewmovieClass nmc)
    {

        if (ModelState.IsValid)
      {
            _db.Add(nmc);
            await _db.SaveChangesAsync();
            return RedirectToAction("Index");

        }
        return View(nmc);
    }
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement