You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC整合视图:在Movie创建页添加Owner下拉选择框

实现创建Movie时关联Owner的下拉选择框

第一步:修正实体关系与模型

当前Movie类里的ICollection<Owner>表示多对多关系,但你的需求是创建Movie时选择单个所有者,更合理的是一对多关系(一个Owner可拥有多个Movie,一个Movie属于一个Owner)。调整Movie模型:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcMovie.Models
{
    public class Movie
    {
        public int Id { get; set; }
        public string? Title { get; set; }

        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }
        public string? Genre { get; set; }

        [Column(TypeName = "decimal(18, 2)")] 
        public decimal Price { get; set; }

        // 外键:关联Owner的Id
        public int OwnerId { get; set; }
        // 导航属性:表示该Movie所属的Owner
        public virtual Owner Owner { get; set; }
    }
}

给Owner模型添加显示优化和可选导航属性:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace MvcMovie.Models
{
    public class Owner
    {
        public int Id { get; set; }
        
        [Display(Name = "First Name")]
        public string Name { get; set; }
        
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
        
        [Display(Name = "Address")]
        public string Adress { get; set; }

        // 计算属性:用于下拉框显示全名
        public string FullName => $"{Name} {LastName}";
        
        // 可选:导航属性,显示该Owner拥有的所有Movie
        public virtual ICollection<Movie> Movies { get; set; } = new List<Movie>();
    }
}

第二步:更新控制器的Create方法

GET请求时把所有Owner数据传到视图,POST请求时接收并保存OwnerId:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MvcMovie.Models;
using System.Threading.Tasks;

namespace MvcMovie.Controllers
{
    public class MoviesController : Controller
    {
        private readonly MvcMovieContext _context;

        public MoviesController(MvcMovieContext context)
        {
            _context = context;
        }

        // 其他CRUD方法保持不变...

        // GET: Movies/Create
        public async Task<IActionResult> Create()
        {
            // 把Owner列表传到视图,用FullName作为显示文本
            ViewData["OwnerId"] = new SelectList(await _context.Owner.ToListAsync(), "Id", "FullName");
            return View();
        }

        // POST: Movies/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price,OwnerId")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                _context.Add(movie);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            // 验证失败时重新传入Owner列表,保持选中状态
            ViewData["OwnerId"] = new SelectList(await _context.Owner.ToListAsync(), "Id", "FullName", movie.OwnerId);
            return View(movie);
        }

        // 其他CRUD方法保持不变...
    }
}

第三步:修改Create视图

替换原有的Owners输入框为下拉选择框:

@model MvcMovie.Models.Movie

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

<h1>Create</h1>

<h4>Movie</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" 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="Genre" class="control-label"></label>
                <input asp-for="Genre" class="form-control" />
                <span asp-validation-for="Genre" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <!-- 替换为Owner下拉选择框 -->
            <div class="form-group">
                <label asp-for="OwnerId" class="control-label"></label>
                <select asp-for="OwnerId" asp-items="@ViewBag.OwnerId" class="form-control">
                    <option value="">-- Select Owner --</option>
                </select>
                <span asp-validation-for="OwnerId" 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");}
}

第四步:更新数据库

打开Package Manager Console,执行以下命令完成数据库迁移:

Add-Migration AddOwnerForeignKeyToMovie
Update-Database

内容的提问来源于stack exchange,提问作者Klaus B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 16:25:37