当前位置: 首页 > news >正文

.NET MVC实现电影票管理

.NET MVC(Model-View-Controller)是微软推出的基于 Model-View-Controller 设计模式的 Web 应用框架,属于 ASP.NET Core 的重要组成部分。其核心目标是通过清晰的分层架构实现 高内聚、低耦合 的开发模式,适用于构建可扩展的企业级应用程序。

 Model(模型层)

  • 职责
    负责业务逻辑处理、数据访问与验证,通常与数据库交互(通过 ORM 工具如 Entity Framework)。

  • View(视图层)

  • 职责
    负责用户界面渲染,通常使用 Razor 语法(.cshtml 文件)动态生成 HTML。

Controller(控制器层)

  • 职责
    处理 HTTP 请求、协调 Model 和 View,实现业务逻辑的入口。

Model

namespace MvcMovie.Models
{public class ErrorViewModel{public string? RequestId { get; set; }public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);}
}
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;namespace MvcMovie.Models;public class Movie
{public int Id { get; set; }[StringLength(60, MinimumLength = 3)][Required]public string? Title { get; set; }[Display(Name = "Release Date")][DataType(DataType.Date)]public DateTime ReleaseDate { get; set; }[Range(1, 100)][DataType(DataType.Currency)][Column(TypeName = "decimal(18, 2)")]public decimal Price { get; set; }[RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$")][Required][StringLength(30)]public string? Genre { get; set; }[RegularExpression(@"^[A-Z]+[a-zA-Z0-9""'\s-]*$")][StringLength(5)][Required]public string? Rating { get; set; }
}
using Microsoft.AspNetCore.Mvc.Rendering;namespace MvcMovie.Models;public class MovieGenreViewModel
{public List<Movie>? Movies { get; set; }public SelectList? Genres { get; set; }public string? MovieGenre { get; set; }public string? SearchString { get; set; }
}
using Microsoft.EntityFrameworkCore;
using MvcMovie.Data;namespace MvcMovie.Models;public static class SeedData
{public static void Initialize(IServiceProvider serviceProvider){using (var context = new MvcMovieContext(serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>())){// Look for any movies.if (context.Movie.Any()){return;   // DB has been seeded}context.Movie.AddRange(new Movie{Title = "When Harry Met Sally",ReleaseDate = DateTime.Parse("1989-2-12").ToUniversalTime(),Genre = "Romantic Comedy",Rating = "R",Price = 7.99M},new Movie{Title = "Ghostbusters ",ReleaseDate = DateTime.Parse("1984-3-13").ToUniversalTime(),Genre = "Comedy",Rating = "R",Price = 8.99M},new Movie{Title = "Ghostbusters 2",ReleaseDate = DateTime.Parse("1986-2-23").ToUniversalTime(),Genre = "Comedy",Rating = "R",Price = 9.99M},new Movie{Title = "Rio Bravo",ReleaseDate = DateTime.Parse("1959-4-15").ToUniversalTime(),Genre = "Western",Rating = "R",Price = 3.99M});context.SaveChanges();}}
}

View

部分view代码,完整代码在文末获取。

@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="Rating" class="control-label"></label><input asp-for="Rating" class="form-control" /><span asp-validation-for="Rating" 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><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");}
}

Controller

using Microsoft.AspNetCore.Mvc;namespace MvcMovie.Controllers;public class HelloWorldController : Controller
{public IActionResult Index(){return View();}public IActionResult Welcome(string name, int numTimes = 1){ViewData["Message"] = "Hello " + name;ViewData["NumTimes"] = numTimes;return View();}
}

using Microsoft.AspNetCore.Mvc;
using MvcMovie.Models;
using System.Diagnostics;namespace MvcMovie.Controllers
{public class HomeController : Controller{private readonly ILogger<HomeController> _logger;public HomeController(ILogger<HomeController> logger){_logger = logger;}public IActionResult Index(){return View();}public IActionResult Privacy(){return View();}[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]public IActionResult Error(){return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });}}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using MvcMovie.Data;
using MvcMovie.Models;namespace MvcMovie.Controllers
{public class MoviesController : Controller{private readonly MvcMovieContext _context;public MoviesController(MvcMovieContext context){_context = context;}// GET: Moviespublic async Task<IActionResult> Index(string movieGenre, string searchString){if (_context.Movie == null){return Problem("Entity set 'MvcMovieContext.Movie'  is null.");}// Use LINQ to get list of genres.IQueryable<string> genreQuery = from m in _context.Movieorderby m.Genreselect m.Genre;var movies = from m in _context.Movieselect m;if (!string.IsNullOrEmpty(searchString)){movies = movies.Where(s => s.Title!.ToUpper().Contains(searchString.ToUpper()));}if (!string.IsNullOrEmpty(movieGenre)){movies = movies.Where(x => x.Genre == movieGenre);}var movieGenreVM = new MovieGenreViewModel{Genres = new SelectList(await genreQuery.Distinct().ToListAsync()),Movies = await movies.ToListAsync()};return View(movieGenreVM);}// GET: Movies/Details/5public async Task<IActionResult> Details(int? id){if (id == null){return NotFound();}var movie = await _context.Movie.FirstOrDefaultAsync(m => m.Id == id);if (movie == null){return NotFound();}return View(movie);}// GET: Movies/Createpublic IActionResult Create(){return View();}// POST: Movies/Create// To protect from overposting attacks, enable the specific properties you want to bind to.// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.[HttpPost][ValidateAntiForgeryToken]public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price,Rating")] Movie movie){if (ModelState.IsValid){movie.ReleaseDate = movie.ReleaseDate.ToUniversalTime();_context.Add(movie);await _context.SaveChangesAsync();return RedirectToAction(nameof(Index));}return View(movie);}// GET: Movies/Edit/5public async Task<IActionResult> Edit(int? id){if (id == null){return NotFound();}var movie = await _context.Movie.FindAsync(id);if (movie == null){return NotFound();}return View(movie);}// POST: Movies/Edit/5// To protect from overposting attacks, enable the specific properties you want to bind to.// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.[HttpPost][ValidateAntiForgeryToken]public async Task<IActionResult> Edit(int id, [Bind("Id,Title,ReleaseDate,Genre,Price,Rating")] Movie movie){if (id != movie.Id){return NotFound();}if (ModelState.IsValid){try{_context.Update(movie);await _context.SaveChangesAsync();}catch (DbUpdateConcurrencyException){if (!MovieExists(movie.Id)){return NotFound();}else{throw;}}return RedirectToAction(nameof(Index));}return View(movie);}// GET: Movies/Delete/5public async Task<IActionResult> Delete(int? id){if (id == null){return NotFound();}var movie = await _context.Movie.FirstOrDefaultAsync(m => m.Id == id);if (movie == null){return NotFound();}return View(movie);}// POST: Movies/Delete/5[HttpPost, ActionName("Delete")][ValidateAntiForgeryToken]public async Task<IActionResult> DeleteConfirmed(int id){var movie = await _context.Movie.FindAsync(id);if (movie != null){_context.Movie.Remove(movie);}await _context.SaveChangesAsync();return RedirectToAction(nameof(Index));}private bool MovieExists(int id){return _context.Movie.Any(e => e.Id == id);}}
}

完整代码:

https://download.csdn.net/download/XiaoWang_csdn/90418392

相关文章:

.NET MVC实现电影票管理

.NET MVC&#xff08;Model-View-Controller&#xff09;是微软推出的基于 Model-View-Controller 设计模式的 Web 应用框架&#xff0c;属于 ASP.NET Core 的重要组成部分。其核心目标是通过清晰的分层架构实现 高内聚、低耦合 的开发模式&#xff0c;适用于构建可扩展的企业级…...

自媒体账号管理工具:创作罐头使用指南

创作罐头使用指南 1. 关于创作罐头 创作罐头是免费的一站式自媒体运营工具&#xff0c;支持各大自媒体平台多账号管理、全网爆文库、原创检测、视频一键分发、团队管理、各平台数据分析等功能。 2. 安装与注册 2.1. 如何安装创作罐头 从我们的官网下载并安装软件 www.czgts.…...

基于数据可视化+SpringBoot+安卓端的数字化OA公司管理平台设计和实现

博主介绍&#xff1a;硕士研究生&#xff0c;专注于信息化技术领域开发与管理&#xff0c;会使用java、标准c/c等开发语言&#xff0c;以及毕业项目实战✌ 从事基于java BS架构、CS架构、c/c 编程工作近16年&#xff0c;拥有近12年的管理工作经验&#xff0c;拥有较丰富的技术架…...

VSCode离线安装插件

最近在其他电脑设备上部署vscode环境出现问题&#xff0c;在vscode里直接安装插件失败&#xff0c;软件提示如下&#xff1a;&#xff08;此前已经用此方法安装过中文插件&#xff09; 这里我们选择手动下载&#xff0c;会自动在浏览器中跳转到该插件的下载链接并自动下载插件&…...

基于Hadoop的汽车大数据分析系统设计与实现【爬虫、数据预处理、MapReduce、echarts、Flask】

文章目录 有需要本项目的代码或文档以及全部资源&#xff0c;或者部署调试可以私信博主 项目介绍爬虫数据概览HIve表设计Cars Database Tables 1. cars_data2. annual_sales_volume3. brand_sales_volume4. city_sales_volume5. sales_volume_by_year_and_brand6. sales_distri…...

SHELL32!Shell_MergeMenus函数分析

SHELL32!Shell_MergeMenus函数分析 UINT Shell_MergeMenus( [in] HMENU hmDst, [in] HMENU hmSrc, UINT uInsert, UINT uIDAdjust, UINT uIDAdjustMax, ULONG uFlags ); 参数 [in] hmDst 类型&#xff1a; HMENU 要向其添加 hmSrc…...

华为云deepseek大模型平台:deepseek满血版

华为云硅基流动使用Chatbox接入DeepSeek-R1满血版671B 1、注册&#xff1a; 华为云deepseek大模型平台注册&#xff1a;https://cloud.siliconflow.cn/i/aDmz6aVN 说明&#xff1a;填写邀请码的话邀请和被邀请的账号都会获得2000 万 Tokens&#xff1b;2个帐号间不会与其他关联…...

AutoGen 技术博客系列 八:深入剖析 Swarm—— 智能体协作的新范式

本系列博文在掘金同步发布, 更多优质文章&#xff0c;请关注本人掘金账号&#xff1a; 人肉推土机的掘金账号 AutoGen系列一&#xff1a;基础介绍与入门教程 AutoGen系列二&#xff1a;深入自定义智能体 AutoGen系列三&#xff1a;内置智能体的应用与实战 AutoGen系列四&am…...

从零开始开发纯血鸿蒙应用之网页浏览

从零开始开发纯血鸿蒙应用 〇、前言一、优化菜单交互1、BuilderFunction.ets2、改造 PageTitleBar 二、网址打开1、方式选择1、使用浏览器打开2、内部打开2.1、声明权限2.2、封装 WebViewPage2.2.1、组件字段2.2.2、aboutToAppear2.2.3、onBackPress2.2.4、标题栏2.2.4、网页内…...

【大模型LLM】DeepSeek LLM Scaling Open-Source Language Models with Longtermism

深度探索LLM&#xff1a;以长期主义扩展开源语言模型 0.论文摘要 开源大语言模型&#xff08;LLMs&#xff09;的快速发展确实令人瞩目。然而&#xff0c;以往文献中描述的扩展规律得出了不同的结论&#xff0c;这为LLMs的扩展蒙上了一层阴影。我们深入研究了扩展规律&#…...

分布式事务-本地消息表学习与落地方案

本文参考&#xff1a; 数据库事务系列04-本地消息表实现分布式事务 基础概念 本地消息表实现分布式事务最终一致性的核心&#xff1a;是通过上游本地事务的原子性持久性&#xff0c;配合中间件的重试机制&#xff0c;从而实现调用下游的最终一致性。 这里有几个要点可以解析一…...

Debezium系列之:记录一次源头数据库刷数据,造成数据丢失的原因

Debezium系列之:记录一次源头数据库刷数据,造成数据丢失的原因 一、背景二、查看topic日志信息三、结论四、解决方法一、背景 源头数据库在很短的时间内刷了大量的数据,部分数据在hdfs丢失了 理论上debezium数据采集不会丢失,就需要排查数据链路某个节点是否有数据丢失。 …...

PHP约课健身管理系统小程序源码

&#x1f3cb;️‍♂️ 约课健身管理系统小程序&#xff1a;重塑健身预约体验&#xff0c;引领数字化健身新时代 一款基于ThinkPHPUniapp框架&#xff0c;由米扬精心雕琢的约课健身管理系统小程序&#xff0c;专为健身房、健身工作室、运动会所、运动场馆、瑜伽馆、拳馆等泛健…...

Java之泛型

文章目录 首先接着上一篇&#xff08;集合&#xff09;文章&#xff0c;来个非常牛逼的易错题传统集合问题分析泛型快速入门案例泛型介绍泛型的好处泛型的语法泛型的声明泛型的实例化泛型使用举例泛型使用的注意事项和细节 自定义泛型自定义泛型方法 自定义泛型接口自定义泛型方…...

图论 之 最小生成树

文章目录 题目1584.连接所有点的最小费用 最小生成树MST&#xff0c;有两种算法进行求解&#xff0c;分别是Kruskal算法和Prim算法Kruskal算法从边出发&#xff0c;适合用于稀疏图Prim算法从顶点出发&#xff0c;适合用于稠密图&#xff1a;基本思想是从一个起始顶点开始&#…...

STM32-有关内存堆栈、map文件

STM32堆栈空间大小设置_stm32堆栈分配大小-CSDN博客 STM32堆栈的大小及内存四&#xff08;五&#xff09;区的分析 - 天街小雨润地狠 - 博客园 .map文件的位置...

Linux系统中常见的词GNU是什么意思?

GNU 是 “GNU’s Not Unix” 的递归缩写&#xff0c;它是一个自由软件项目&#xff0c;旨在创建一个完全自由的操作系统。这个名字反映了GNU项目的核心理念&#xff1a;它试图创建一个类Unix的系统&#xff0c;但不是Unix本身。 GNU 项目由 理查德斯托曼&#xff08;Richard S…...

【个人开源】——从零开始在高通手机上部署sd(二)

代码&#xff1a;https://github.com/chenjun2hao/qualcomm.ai 推理耗时统计 单位/ms 硬件qnncpu_clipqnncpu_unetqnncpu_vaehtp_cliphtp_unethtp_vae骁龙8 gen124716.994133440.39723.215411.097696.327 1. 下载依赖 下载opencv_x64.tar,提取码: rrbp下载opencv_aarch64.t…...

【MCU驱动开发概述】

MCU驱动开发概述 目录 MCU驱动开发概述二、驱动开发的目的三、驱动开发的关键组成部分四、示例 - LED 控制驱动 一、引言 MCU&#xff08;Microcontroller Unit&#xff09;&#xff0c;即微控制器单元&#xff0c;是一种集成在单个芯片上的计算机系统&#xff0c;通常用于控制…...

PC端Linux之虚拟CAN

在调试QT程序时候需要用到虚拟CAN进行发送和接收的操作&#xff0c;以此记录方法。 在调试QT程序时候需要用到虚拟CAN进行发送和接收的操作&#xff0c;以此记录方法。 1、安装can-utils sudo apt install can-utils ifconig -a【查看是否安装成功&#xff0c;是否有can0网络…...

Windows优化工具深度评测:告别卡顿,一键提升系统性能

Windows优化工具深度评测&#xff1a;告别卡顿&#xff0c;一键提升系统性能 【免费下载链接】winutil Chris Titus Techs Windows Utility - Install Programs, Tweaks, Fixes, and Updates 项目地址: https://gitcode.com/GitHub_Trending/wi/winutil 你是否也曾经历过…...

如何将网页内容快速转换为Markdown格式:MarkDownload完整使用指南

如何将网页内容快速转换为Markdown格式&#xff1a;MarkDownload完整使用指南 【免费下载链接】markdownload A Firefox and Google Chrome extension to clip websites and download them into a readable markdown file. 项目地址: https://gitcode.com/gh_mirrors/ma/mark…...

告别先查后改!用MyBatis-Plus-Plus实现复合主键批量更新,性能提升实测

告别先查后改&#xff01;用MyBatis-Plus-Plus实现复合主键批量更新&#xff0c;性能提升实测 在数据密集型应用中&#xff0c;批量更新操作往往是性能瓶颈所在。当数据量达到万级甚至十万级时&#xff0c;传统的"先查询再修改"模式会带来巨大的数据库压力。本文将深…...

抖音下载器完整教程:3分钟掌握免费批量下载技巧

抖音下载器完整教程&#xff1a;3分钟掌握免费批量下载技巧 【免费下载链接】douyin-downloader A practical Douyin downloader for both single-item and profile batch downloads, with progress display, retries, SQLite deduplication, and browser fallback support. 抖…...

番茄小说下载器终极指南:3步打造你的永久离线图书馆

番茄小说下载器终极指南&#xff1a;3步打造你的永久离线图书馆 【免费下载链接】fanqienovel-downloader 下载番茄小说 项目地址: https://gitcode.com/gh_mirrors/fa/fanqienovel-downloader fanqienovel-downloader 是一款强大的开源工具&#xff0c;专门用于下载番茄…...

AI催眠师:模型行为矫正专家

从“黑盒”到“可引导”的模型测试新范式在软件测试的传统疆域里&#xff0c;我们习惯于与确定性的代码逻辑、清晰的输入输出边界以及可复现的缺陷打交道。然而&#xff0c;随着以大型语言模型&#xff08;LLM&#xff09;为代表的生成式人工智能系统成为核心组件&#xff0c;测…...

华硕笔记本终极控制方案:G-Helper 3分钟快速上手指南

华硕笔记本终极控制方案&#xff1a;G-Helper 3分钟快速上手指南 【免费下载链接】g-helper Lightweight, open-source control tool for ASUS laptops and ROG Ally. Manage performance modes, fans, GPU, battery, and RGB lighting across Zephyrus, Flow, TUF, Strix, Sca…...

Spring Boot 4.0 Agent-Ready 架构实战手册(仅限首批内测团队使用的7条黄金配置守则)

第一章&#xff1a;Spring Boot 4.0 Agent-Ready 架构概览与演进脉络Spring Boot 4.0 标志着 JVM 应用可观测性与运行时可插拔能力的重大跃迁。其核心设计目标是原生支持 Java Agent 的零侵入式集成&#xff0c;使 APM、安全审计、链路追踪等能力不再依赖启动参数硬编码或定制化…...

MZmine 4.5.0:质谱数据处理架构优化与算法性能深度解析

MZmine 4.5.0&#xff1a;质谱数据处理架构优化与算法性能深度解析 【免费下载链接】mzmine3 mzmine source code repository 项目地址: https://gitcode.com/gh_mirrors/mz/mzmine3 在代谢组学和蛋白质组学研究领域&#xff0c;大规模质谱数据的处理效率直接决定了科研…...

从‘猜’到‘懂’:用LIME和SHAP给你的机器学习模型做一次‘可解释性体检’(对比与选型指南)

从‘猜’到‘懂’&#xff1a;用LIME和SHAP给你的机器学习模型做一次‘可解释性体检’&#xff08;对比与选型指南&#xff09; 在医疗诊断中&#xff0c;医生往往需要借助X光、CT等影像学检查来了解患者体内的情况。类似地&#xff0c;当我们面对一个表现优异但内部机制复杂的…...