如何使用两个外键引用添加下拉列表
How to add Dropdownlist using two foreign key References
我有三个table:
MoviesTable
- 由 Movieid
[PK] 和年份、发布日期等详细信息组成
Genre
- 包含 Genreid
[PK] 和 GenreNames
[nvarchar] 包含戏剧、动作、喜剧等
MovieGenre
- moviegenreid
[PK], Genreid
[int][FK], Movieid
[int][FK]
我想更改表格以适应流派的多个值,而不是接受一个。
我以前的代码在这里,只用了两个 tables Moviestable 和 Genre table 作为下拉菜单。我的目的是通过使用与“Movieid”和“Genreid”的外键关系来实现下拉列表接受倍数值
可以吗,如果可以,我会怎么修改?
主类
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");}
}
首先你必须添加 Select2 js Libraray
的引用
在Create.cshtml
<select name="GenreIds" class="form-control" multiple="multiple" asp-items="@viewbag.GenreId">
</select>
在控制器中 Post 动作
[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);
}
我有三个table:
MoviesTable
- 由Movieid
[PK] 和年份、发布日期等详细信息组成Genre
- 包含Genreid
[PK] 和GenreNames
[nvarchar] 包含戏剧、动作、喜剧等MovieGenre
-moviegenreid
[PK],Genreid
[int][FK],Movieid
[int][FK]
我想更改表格以适应流派的多个值,而不是接受一个。
我以前的代码在这里,只用了两个 tables Moviestable 和 Genre table 作为下拉菜单。我的目的是通过使用与“Movieid”和“Genreid”的外键关系来实现下拉列表接受倍数值
可以吗,如果可以,我会怎么修改?
主类
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");}
}
首先你必须添加 Select2 js Libraray
的引用在Create.cshtml
<select name="GenreIds" class="form-control" multiple="multiple" asp-items="@viewbag.GenreId">
</select>
在控制器中 Post 动作
[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);
}