<!doctype html> <html lang="zh"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link href="https://www.jb51.net/~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link href="https://www.jb51.net/~/css/site.css" /> <title>@ViewData["title"]-舒适快捷经济</title> </head>
使用ViewBag
这是所谓的动态类型,直接无中生有造一个属性
ViewBag.list=new NewsManager().GetNews(4);
视图中引用
@foreach (News item in @ViewBag.list) { <div> <div> <a href="/News/NewsDetail?id=@item.Id" >@item.NewsTitle</a> </div> <div> @item.PublishTime.ToShortDateString() </div> </div>
使用viewmodel
控制器中使用View的重载方法传递viewmodel
public IActionResult Index() { ViewData["title"]="好运来酒店"; return View(new NewsManager().GetNews(4)); }
视图中先声明后使用
Specify a model using the @model directive. Use the model with @Model:
@model list<News> ... @foreach (News item in @Model) { <div> <div> <a href="/News/NewsDetail?id=@item.Id" >@item.NewsTitle</a> </div> <div> @item.PublishTime.ToShortDateString() </div> </div>
修改后的首页
9.分部视图
创建分部视图
分部视图的创建和其他视图的创建没有任何区别,只是它作为其他视图的一部分来视图用。
避免视图代码的重复。
在其他视图中使用分部视图
引用分部视图使用特殊的标签 <partial />
@model List<News> <div> <div> <partial /> </div> <div> <div>您现在所在的位置:中式餐厅酒店>新闻动态</div> <div> @foreach (News item in @Model) { <div> <div><a href="NewsDetail?id=@item.Id" >@item.NewsTitle</a></div> <div>@item.PublishTime.ToShortDateString()</div> </div> } </div> </div> </div>
10.使用Section布局定义
@RenderSection("js",required:false)
使用
@section js{ <script type="text/javascript"> function changeFontSize(fontSize) { //获取要变化的对象 var divContent = $(".row .m-4"); divContent.css("font-size",fontSize); } </script> }
11.表单验证
使用模型验证方式实现
添加验证特性
public partial class DishBook { public uint Id { get; set; } public string HotelName { get; set; } [Required(ErrorMessage = "{0}不能为空")] [Display(Name = "消费时间")] public DateTime? ConsumeTime { get; set; } [Required(ErrorMessage = "{0}不能为空")] [RegularExpression(@"^\d+$", ErrorMessage = "请输入正确的{0}")] [Display(Name = "消费人数")] public uint? ConsumePersons { get; set; } public string RoomType { get; set; } [Required(ErrorMessage = "{0}不能为空")] [RegularExpression(@"^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$", ErrorMessage = "请输入正确的{0}")] [Display(Name = "手机号码")] public string CustomerPhone { get; set; } [Required(ErrorMessage = "{0}不能为空")] [Display(Name = "姓名")] public string CustomerName { get; set; } [EmailAddress(ErrorMessage = "请输入正确的{0}")] [Display(Name = "电子邮件")] public string CustomerEmail { get; set; } public string Comments { get; set; } public DateTime BookTime { get; set; } public int? BookStatus { get; set; } // 扩展属性 [Required(ErrorMessage = "{0}不能为空")] [Remote(action:"CheckVcode",controller:"Dish")] [Display(Name = "验证码")] public string ValidationCode { get; set; } }
使用 Tag Helper 完成前端代码编写