【问题标题】:How to add Dropdownlist using two foreign key References如何使用两个外键引用添加下拉列表
【发布时间】:2021-05-02 05:37:30
【问题描述】:

我有三张桌子:

  1. MoviesTable - 由Movieid [PK] 和年份、发布日期等详细信息组成。
  2. Genre - 包含 Genreid [PK] 和 GenreNames [nvarchar] 包括戏剧、动作、喜剧等。
  3. MovieGenre - moviegenreid [PK], Genreid [int][FK], Movieid [int][FK]

我想更改表单以适应类型的多个值,而不是接受一个。

我之前的代码在这里,只使用了两个表 Moviestable 和 Genre 表作为下拉列表。我的意图是通过使用与“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>
   

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

【问题讨论】:

    标签: sql-server visual-studio drop-down-menu asp.net-core-mvc asp.net-core-3.1


    【解决方案1】:

    首先你必须添加Select2 js Libraray的引用

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

    【讨论】:

    • 先生,很有帮助,但 dbcontextclass 中的无关代码为 `` Modelbuilder.Entity().HasKey(mg => new{ mg.MovieId, mg.GenreId }); Modelbuilder.Entity() .HasOne(g => g.NewmovieClasses) .WithMany(m => m.MovieGenre) .HasForeignKey(j => j.MovieId); Modelbuilder.Entity() .HasOne(g => g.GenreClasses) .WithMany(m => m.MovieGenre) .HasForeignKey(j => j.GenreId); ```对吗?
    • 但实际上我无法获取创建视图的代码!
    • 你是什么意思>但我实际上无法获得创建视图的代码!
    猜你喜欢
    • 2017-02-13
    • 2011-03-05
    • 2020-12-18
    • 2016-03-19
    • 1970-01-01
    • 2014-06-04
    • 2016-10-22
    • 2016-08-25
    • 1970-01-01
    相关资源
    最近更新 更多