1. Razor常用

  1. @model List<WebMvc.Models.Student>
  2. @{
  3. ViewBag.Title = "List";
  4. string htmlSpan = "<span style='color:red'>hello</span>";
  5. }
  6. <h2>List</h2>
  7. @Html.Raw(htmlSpan)
  8. <ul>
  9. @foreach (var student in Model)
  10. {
  11. <li>@student.Name</li>
  12. }
  13. </ul>

@model 声明
@{ } 代码区域
@xx 变量
@(a)a@(b) 括号区域表示为代码区域
@* 注释
Html.Raw()方法可以使变量转为html代码

2. 区域

右键项目,新建区域。如果没有区域,则选择新搭建基架的项目中选择MVC5区域
生成结构如下
image.png
Controllers文件夹中新建HomeController
根据Index的Action生成视图。
启动之后
image.png
但是访问外层的Home时出错了
image.png
根据错误提示,我们去外层的RouteConfig中去设置namespaces,之后正常运行。

  1. using System.Web.Mvc;
  2. using System.Web.Routing;
  3. namespace WebMvc
  4. {
  5. public class RouteConfig
  6. {
  7. public static void RegisterRoutes(RouteCollection routes)
  8. {
  9. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  10. routes.MapRoute(
  11. name: "Default",
  12. url: "{controller}/{action}/{id}",
  13. defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  14. namespaces: new string[] { "WebMvc.Controllers" }
  15. );
  16. }
  17. }
  18. }

跳转页面。

  1. // 跨路由跳转
  2. @Html.RouteLink("体育模块", "Sport_default", new { controller = "Home", action = "Index" })
  3. @Html.RouteLink("后台模块", "Admin_default", new { controller = "Home", action = "Index" })
  4. @Html.RouteLink("登录页面", "default", new { controller = "View", action = "Login" })
  5. // 同路由跳转
  6. @Html.ActionLink("ShowData", "ShowData")
  7. // 生成Url : http://localhost:63179/Home/ShowData?name=name
  8. // 同理 Url.RouteUrl 一样如此
  9. <a href="@Url.Action("ShowData",new { name = "name"})">content</a>

3. 补充

ViewModel特性补充

  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. namespace WebMvc.Models
  4. {
  5. public class RegisterViewModel
  6. {
  7. [Required]
  8. [EmailAddress(ErrorMessage = "邮箱地址有误")]
  9. public string Email { get; set; }
  10. [Required]
  11. public string Password { get; set; }
  12. [Required]
  13. [Compare(nameof(Password))]
  14. public string ConfirmPassword { get; set; }
  15. [Range(0, 120, ErrorMessage = "年龄必须在0~120之间")]
  16. public int Age { get; set; }
  17. [Display(Name = "出生日期")]
  18. public DateTime? BornData { get; set; }
  19. }
  20. }

Controller中内部使用的Action可以使用[NoAction]特性标识,这样就无法访问了。
如果需要给Action改名,则使用特性[ActionName]修改。