如何使用两个外键引用添加Dropdownlist [英] How to add Dropdownlist using two foreign key References

查看:75
本文介绍了如何使用两个外键引用添加Dropdownlist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个表:

  1. MoviesTable -由 Movieid [PK]和详细信息(例如年份,发行日期等)组成.
  2. Genre -包含 Genreid [PK]和 GenreNames [nvarchar],由戏剧,动作,喜剧等组成.
  3. MovieGenre - moviegenreid [PK], Genreid [int] [FK], Movieid [int][FK]
  1. MoviesTable - consists of Movieid [PK] and details such as year, release date etc.
  2. Genre - contains Genreid [PK] and GenreNames [nvarchar] consist of drama, actions, comedy etc.
  3. MovieGenre - moviegenreid [PK], Genreid [int][FK], Movieid [int][FK]

我想更改表格以容纳多种风格的值,而不是接受一种.

I want to change the form to accommodate multiple values of genre instead of accepting one.

我以前的代码在这里,仅使用两个表Moviestable和Genre表进行下拉.我的意图是通过将外键关系与"Movieid"一起使用来实现dropdownlist接受多个值.nd"Genreid"

My previous code is here, only used two tables Moviestable and Genre table for dropdown. my intent is to implement dropdownlist accept multiples values by using foreign key relationship with "Movieid" nd "Genreid"

有可能吗?如果要修改什么?

Is that possible?, if,what modification will I d ?

MainClass


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; }

        [Display(Name = "Genre ")]
        public  int GenreId { get; set; }


        //[ForeignKey("GenreId")]
        public GenreClass GName { get; set; }

      
    }
}

控制器

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

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

        
        public MveController(ApplicationDbContext db)
        {
            _db = db;
        }
        public async Task <IActionResult> Index()
        {

            var displaydata = _db.Moviestable.Include(g => g.GName)
                .AsNoTracking();
            return View(await displaydata.ToListAsync());
        }



        //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()

        {
            ViewBag.GenreId = new SelectList(_db.Genre, "GenreId", "GName");
           
            return View();


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

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

            }
            ViewBag.GenreId = new SelectList(_db.Genre, "GenreId", "GName");

            return View(nmc);
        }

        public async Task< IActionResult> Edit(int? id)
        {
            if(id==null)
            {
                return RedirectToAction("Index");
            }

            ViewBag.GenreId = new SelectList(_db.Genre, "GenreId", "GName");
            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");


            }

            ViewBag.GenreId = new SelectList(_db.Genre, "GenreId", "GName");
            return View(mc);

        }

        public async Task<IActionResult> Details(int? id)
        { 
           



            if (id == null)
            {
                return RedirectToAction("Index");
            }


            var getmvedetails = await _db.Moviestable.FindAsync(id);



            _db.Moviestable.Include(g => g.GName);

            await _db.SaveChangesAsync();

            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");
        }

       
        
           

           
           
       
        

       
    }
}

DBContext

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


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

        }

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

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

        //protected override void OnModelCreating(ModelBuilder Modelbuilder)
        //{
        //    Modelbuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");


        //    Modelbuilder.Entity<NewmovieClass>().HasOne(g => g.GName).WithMany(m => m.newmovieClasses).HasForeignKey(g => g.GenreId);


        //    Modelbuilder.Entity<GenreClass>().ToTable("Genre");

        //    OnModelCreatingPartial(Modelbuilder);
        //}
        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);


        public DbSet<MovieGenreClass> MovieGenre { get; set; }

    }

    }

Index.cshtml

@*@ViewBag.Header*@



@model IEnumerable<Moviesite.Models.NewmovieClass>

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

  
}




<h1 style="color:brown"> Latest Movies </h1>





<p>
    <a asp-action="Create">Add new Movie</a>
</p>

<form method="get" asp-action="Index">

    <p>
        <input type="search" placeholder="Enter Movie Title or Description..." value="@ViewData["Getmoviedetails"]" name="Mvesearch" style="width:500px;"/>
        <input type ="submit" value="Search" class="btn btn-secondary"/>
       <a asp-action="Index">Get All Movies</a>
    </p>
</form>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Movieid)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Movietitle)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Description)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Storyline)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Year)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Releasedate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Runtime)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.MovieType)
            </th>
           <th>
               @Html.DisplayNameFor(model => model.GenreId)
           </th>
            
            <th>

            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {

        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Movieid)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Movietitle)

            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Description)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Storyline)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Year)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Releasedate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Runtime)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.MovieType)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.GName.GName)

            </td>

            
            <td>



                @Html.ActionLink("Edit", "Edit", new { id = item.Movieid }, new { @class = "btn btn-primary btn-sm" })
                @Html.ActionLink("Details", "Details", new { id = item.Movieid }, new { @class = "btn btn-success btn-sm" })
                @Html.ActionLink("Delete", "Delete", new { id = item.Movieid }, new { @class = "btn btn-danger btn-sm" })

            </td>






        </tr>

        }

    </tbody>
</table>
   

Create.Cshtml

@using  Moviesite.Enums
@model Moviesite.Models.NewmovieClass

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

<h1>Create</h1>

<h4 style="color:crimson">Add a movie to list</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">



            <div class="form-group">
                <label asp-for="Movietitle" class="control-label"></label>
                <input asp-for="Movietitle" class="form-control" />
                <span asp-validation-for="Movietitle" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Storyline" class="control-label"></label>
                <input asp-for="Storyline" class="form-control" />
                <span asp-validation-for="Storyline" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Year" class="control-label"></label>
                <input asp-for="Year" class="form-control" />
                <span asp-validation-for="Year" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Releasedate" class="control-label"></label>
                <input asp-for="Releasedate" class="form-control" />
                <span asp-validation-for="Releasedate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Runtime" class="control-label"></label>
                <input asp-for="Runtime" class="form-control" />
                <span asp-validation-for="Runtime" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="MovieType" class="control-label"></label>
                <select asp-for="MovieType" class="form-control" asp-items="Html.GetEnumSelectList<Mvetypenum>()">
                    <option value="">Select movie type</option>
                </select>
                <span asp-validation-for="MovieType" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label asp-for="GenreId" class="control-label"></label>
                @Html.DropDownList("GenreId", null, htmlAttributes: new { @class = "form-control" })
                
                @*<option value="">Select movie Genre</option>*@
                <span asp-validation-for="GenreId" 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");}
}

推荐答案

首先,您必须添加在Create.cshtml

in Create.cshtml

 <select name="GenreIds" class="form-control" multiple="multiple" asp-items="@viewbag.GenreId">
</select>

在操作后的控制台中



           [HttpPost]
           public async Task<IActionResult> Create([Bind("Movieid,Movietitle,Description,Storyline,Year,Releasedate,Runtime,MovieType")] NewmovieClass nmc,int[] GenreIds)
           {
   
               if (ModelState.IsValid)
              { 
                   _db.Add(nmc);
                   await _db.SaveChangesAsync();
                   foreach(var item in GenreIds)
                    {
                       MovieGenre movieGenre=new MovieGenre();
                       movieGenre.Genreid=item;
                       movieGenre.movieid=nmc.id;
                        _db.Add(movieGenre);
                     
                    }
                    await _db.SaveChangesAsync();
                   return RedirectToAction("Index");
   
               }
               ViewBag.GenreId = new SelectList(_db.Genre, "GenreId", "GName");
   
               return View(nmc);
           }




这篇关于如何使用两个外键引用添加Dropdownlist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆