一, Application_Start
想着记录一下 MVC 的一些基础知识, 但是感觉比较杂乱, 那就从启动开始吧. 我们启动一个 MVC 项目时, 响应第一次请求的是 Global.asax.cs 文件中的 Application_Start 方法. 我们先来看下它里面做了什么事情.
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();// 注册区域路由
- GlobalConfiguration.Configure(webApiConfig.Register);// 注册 webapi 路由
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);//
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- BundleConfig.RegisterBundles(BundleTable.Bundles);
- }
该方法执行了一些初始化的工作, 注册 Route, Filter, Bundle.Route 之前的文章已经有讲过, Filter 后面再专门讲. 那么 Bundle 是做什么的呢. 它是添加了一些必要的 JS 和 CSS, 以便在_Layout 中引用, 避免写很多的引入文件.
- public class BundleConfig
- {
- // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
- public static void RegisterBundles(BundleCollection bundles)
- {
- bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
- "~/Scripts/jquery-{version}.js"));
- bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
- "~/Scripts/jquery.validate*"));
- // Use the development version of Modernizr to develop with and learn from. Then, when you're
- // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
- bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
- "~/Scripts/modernizr-*"));
- bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
- "~/Scripts/bootstrap.js",
- "~/Scripts/respond.js"));
- bundles.Add(new StyleBundle("~/Content/css").Include(
- "~/Content/bootstrap.css",
- "~/Content/site.css"));
- }
- }
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>
- @ViewBag.Title - 我的 ASP.NET 应用程序
- </title>
- @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr")
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar">
- </span>
- <span class="icon-bar">
- </span>
- <span class="icon-bar">
- </span>
- </button>
- @HTML.ActionLink("应用程序名称", "Index", "Home", new { area = ""}, new { @class
- ="navbar-brand" })
- </div>
- <div class="navbar-collapse collapse">
- <ul class="nav navbar-nav">
- <li>
- @HTML.ActionLink("主页", "Index", "Home")
- </li>
- <li>
- @HTML.ActionLink("关于", "About", "Home")
- </li>
- <li>
- @HTML.ActionLink("联系方式", "Contact", "Home")
- </li>
- </ul>
- </div>
- </div>
- </div>
- <div class="container body-content">
- @RenderBody()
- <hr />
- <footer>
- <p>
- © @DateTime.Now.Year - 我的 ASP.NET 应用程序
- </p>
- </footer>
- </div>
- @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap")
- @RenderSection("scripts", required: false)
- </body>
- </HTML>
_Layout 文件中通过 @Scripts.Render 和 @Styles.Render 去引入. 同时可以看到在_Layout 布局页中有 @RenderBody() 和 @RenderSection("scripts", required: false) 这两个,@RenderBody 显示内容页的内容,@RenderSection 留给内容页添加自己需要的内容, 其中 required 参数如果为 true 或留空, 内容页则必须包含该 section 节点.
那么这个时候可能会想_Layout 文件是怎么加载的, 其实是在 Views/_ViewStart.cshtml 中指定的, 因为 MVC 在渲染视图时会先去 Views 文件夹下找_ViewStart, 在里面指定了 Layout.
- @{
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
二, 数据传值的几种方式
1,ViewData:ViewData 是 ViewDataDictionary 类型, 本质上是一个 Dictionary, 它的调用方式
- ViewData["User"] = new User()
- {
- Id = 7,
- Name = "张三",
- Account = "zhangshan"
- };
取值的时候需要进行类型转换
User userViewData = ViewData["User"] as User;
2,ViewBag:ViewBag 是 dynamic 类型的, 它可以直接通过 点 来赋值
- ViewBag.Something = 23456;
- ViewBag.Name = "Eleven";
- ViewBag.Description = "Teacher";//JS
- ViewBag.User = new User()
- {
- Id = 7,
- Name = "张三",
- Account = "",
- };
取值的时候可以直接使用
User userViewBag = ViewBag.User;
3,TempData:TempData 是 TempDataDictionary 类型, 和 ViewData 相似, 不同的是它是基于 session 的, 可以跨 action 访问, 而 ViewData 和 ViewBag 无法跨 action.
- public ActionResult Action1{
- TempData["User"] = new User()
- {
- Id = 7,
- Name = "张三",
- Account = "zhangsan",
- };
- return this.RedirectToAction("TempDataPage");
- }
- public ActionResult TempDataPage()
- {
- base.ViewBag.User = base.TempData["User"];
- return View();
- }
三, Razor 视图
@字符:@是 Razor 中的一个重要符号, 它被定义为 Razor 服务器代码块的开始符号.
1. 行内标记:@DateTime.Now.ToString("yyyy-MM-dd")
2. 单行标记:@{ string name = "张三"; string name2 = "李四";}
3. 多行标记:
- @{
- var age = 25;
- Response.Write("Age:" + age);
- }
4. 在遇到如 if,for,while 等具有 "keyword(){}" 形式的 C# 代码结构时, Razor 标记可以写成 "@keyword(){}" 这样的特殊形式.
- @if (1> 2)
- {
- <p>1> 2</p>
- }
- else
- {
- <p>1 <2</p>
- }
5. 服务器代码里嵌入 HTML 代码
在 Razor 标记的代码中如果有成对的 HTML 标记, 则这个标记及其内容会被当作普通文本输出.
在 Razor 标记的代码中如果有 "@:", 则其后的一行代码会被当作普通文本输出.
在 Razor 标记的代码中如果有 < text> </text > 标记, 则其内容会被当作普通文本输出
四, HtmlHelper/AjaxHelper
@HTML.ActionLink:
ActionLink 用来生成 HTML 中的 a 标签, LinkText 是链接显示出的文字, 如果 ActionLink 的参数中给出 Controller 则链接指向对应的 Controller 下的 Action. 如果没有给出 Controller 则指向当前页面对应的 Controller 下的 Action. 如果 ActionLink 的参数中给出要传递的参数, 如 id, 则在链接的最后写出 id 值.
- @HTML.ActionLink("LinkText", "RazorShow")
- @HTML.ActionLink("带控制器", "ActionName", "ControllerName")
- @HTML.ActionLink("带路由信息", "ActionName", new { id = 1, name = 3, age = 4, height = 5 })
- <a href="/Html/ActionName/1?name=3&age=4&height=5"> 带路由信息 </a>
- @HTML.ActionLink("链接", "action", new { id = 1, name = 3, age = 4, height = 5 }, new { @class = "classText", style = "width:200px", tt = "xxx" })
- @HTML.RouteLink:
RouteLink 同样是用来生成 HTML 中的 a 标签的, 但是其参数和 ActionLink 不同, LinkText 依然是链接显示的文字, 而链接的其他信息则包含在 RouteLink 的第二个参数中. 这个参数是个 Object, 它的 action 属性表示指向的 Action 而 controller 属性表示指向的 Controller. 如果没有 controller 属性则指向当前 Controller.id 属性则为要传递的参数.
- @HTML.RouteLink("LinkText", new {
- action = "ActionName"
- })
- @HTML.RouteLink("LinkText", new {
- action = "ActionName", controller = "ControllerName"
- })
- @HTML.RouteLink("LinkText", new {
- action = "ActionName", id = 1
- })
System.Web.Mvc.HTML 下还有很多其他的扩展, 比如 InputExtensions,FormExtensions
- @HTML.DropDownList("NameId", list)
- @HTML.RadioButton("NameId", "Value", true)
- @using (HTML.BeginForm("PostData", "Html", FormMethod.Get))
- {
- @HTML.TextBox("username")
- @HTML.Password("password")
- <input type="submit" value="提交" />
- }
- <p > 等于 webform 的 ascx</p>
- <p>HTML.RenderPartial 在指定位置添加一个 view, 返回 void 需要放入大括号 </p>
- @{HTML.RenderPartial("PartialPage", "这里是 Html.RenderPartial");}
- <p>HTML.Partial 返回的是字符串, 放入当前位置 </p>
- @HTML.Partial("PartialPage", "这里是 Html.Partial")
- <p>HTML.Action 返回的是字符串, 放入当前位置, 需要经过 action 的处理 </p>
- @HTML.Action("Render", "Second", new { name = "Html.Action" })
- <p>HTML.RenderAction 在指定位置添加一个 view, 返回 void 需要放入大括号, 需要经过 action 的处理 </p>
- @{HTML.RenderAction("Render", "Second", new { name = "Html.RenderAction" });}
@Ajax.BeginForm: 异步调用
@Ajax.BeginForm("actionname", new AjaxOptions() { HttpMethod="Post" });
五, 分布视图: PartialView
- [ChildActionOnly]// 不能被单独请求
- public ActionResult Render()
- {
- ViewBag.Name = "jesen";
- return PartialView() // 指定分部视图, 在_ViewStatrt.cshtml 中指定的 Layout 会无效
- }
- <p>HTML.RenderPartial 在指定位置添加一个 view, 返回 void 需要放入大括号 </p>
- @{HTML.RenderPartial("PartialPage", "这里是 Html.RenderPartial");}
- <p>HTML.Partial 返回的是字符串, 放入当前位置 </p>
- @HTML.Partial("PartialPage", "这里是 Html.Partial")
来源: http://www.bubuko.com/infodetail-3090893.html