1. Razor常用
@model List<WebMvc.Models.Student>@{ViewBag.Title = "List";string htmlSpan = "<span style='color:red'>hello</span>";}<h2>List</h2>@Html.Raw(htmlSpan)<ul>@foreach (var student in Model){<li>@student.Name</li>}</ul>
@model 声明@{ } 代码区域@xx 变量@(a)a@(b) 括号区域表示为代码区域@* 注释Html.Raw()方法可以使变量转为html代码
2. 区域
右键项目,新建区域。如果没有区域,则选择新搭建基架的项目中选择MVC5区域。
生成结构如下
在Controllers文件夹中新建HomeController
根据Index的Action生成视图。
启动之后
但是访问外层的Home时出错了
根据错误提示,我们去外层的RouteConfig中去设置namespaces,之后正常运行。
using System.Web.Mvc;using System.Web.Routing;namespace WebMvc{public class RouteConfig{public static void RegisterRoutes(RouteCollection routes){routes.IgnoreRoute("{resource}.axd/{*pathInfo}");routes.MapRoute(name: "Default",url: "{controller}/{action}/{id}",defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },namespaces: new string[] { "WebMvc.Controllers" });}}}
跳转页面。
// 跨路由跳转@Html.RouteLink("体育模块", "Sport_default", new { controller = "Home", action = "Index" })@Html.RouteLink("后台模块", "Admin_default", new { controller = "Home", action = "Index" })@Html.RouteLink("登录页面", "default", new { controller = "View", action = "Login" })// 同路由跳转@Html.ActionLink("ShowData", "ShowData")// 生成Url : http://localhost:63179/Home/ShowData?name=name// 同理 Url.RouteUrl 一样如此<a href="@Url.Action("ShowData",new { name = "name"})">content</a>
3. 补充
ViewModel特性补充
using System;using System.ComponentModel.DataAnnotations;namespace WebMvc.Models{public class RegisterViewModel{[Required][EmailAddress(ErrorMessage = "邮箱地址有误")]public string Email { get; set; }[Required]public string Password { get; set; }[Required][Compare(nameof(Password))]public string ConfirmPassword { get; set; }[Range(0, 120, ErrorMessage = "年龄必须在0~120之间")]public int Age { get; set; }[Display(Name = "出生日期")]public DateTime? BornData { get; set; }}}
在Controller中内部使用的Action可以使用[NoAction]特性标识,这样就无法访问了。
如果需要给Action改名,则使用特性[ActionName]修改。
