MVC3 Razor视图引擎基础语法详解

4星 · 超过85%的资源 需积分: 10 5 下载量 134 浏览量 更新于2024-09-14 收藏 30KB DOC 举报
MVC3 Razor视图引擎基础语法是MVC框架中的一个重要组成部分,它简化了前端开发过程,尤其是在ASP.NET中构建动态网页。以下是关于MVC3 Razor视图引擎的基础概念和常见用法: 1. **代码块标记**: - Razor视图中的代码以`@`开头,或者使用`@{/*代码体*/}`包裹,这表示这部分代码会被ASP.NET引擎编译和执行。`@{/*代码体*/}`中的每行必须以分号`;`结束,如`@{var i = 10; var j = 20;}`。 2. **字符和字符串处理**: - 字符类型常量需要使用双引号`""`包围,例如`@{string str = "mystring";}`。 - 如果要在页面输出字符`@`,可以使用HTML ASCII编码`&amp;#64;`。 3. **智能分析**: - Razor引擎会根据上下文智能判断是否处理代码。如果`@`前有非空白字符,如`<p>text@ixx</p>`,则会输出原始文本。 4. **局部变量**: - Razor支持在单行或多行代码块中定义局部变量,如单行`@{var total = 7;}`,多行`@{var greeting = "Welcome to our site!"; var weekDay = DateTime.Now.DayOfWeek; var greetingMessage = greeting + "Today is: " + weekDay;}`。 - 变量只能在定义它的上下文中使用,例如`<p>The value of your account is: @total</p>`。 5. **变量拼接**: - 直接拼接变量时,需要确保正确使用,如`@{var i = 10;}`会导致输出`text10text`,而`<p>text@i text</p>`会输出`text10text`。如果要保留`@`符号,需要包裹在表达式中,如`<p>text@{@i}text</p>`。 6. **方法调用**: - 对于方法调用,如`ToString()`,可以直接使用变量名,无需使用`@{}`,但务必保持`@`前有空格,如`<p>text@i.ToString()text</p>`。 通过这些基础语法,开发人员可以高效地编写Razor视图,实现动态内容的插入和控制页面结构。Razor的强大之处在于其简洁的语法和与C#的无缝集成,使得前端开发变得更加直观和易于维护。
2016-03-12 上传
asp.net mvc 自定义视图引擎 public ThemeableRazorViewEngine() { AreaViewLocationFormats = new[] { //themes "~/Areas/{2}/Themes/{3}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Themes/{3}/Views/Shared/{0}.cshtml", //default "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", }; AreaMasterLocationFormats = new[] { //themes "~/Areas/{2}/Themes/{3}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Themes/{3}/Views/Shared/{0}.cshtml", //default "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", }; AreaPartialViewLocationFormats = new[] { //themes "~/Areas/{2}/Themes/{3}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Themes/{3}/Views/Shared/{0}.cshtml", //default "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml" }; ViewLocationFormats = new[] { //themes "~/Themes/{2}/Views/{1}/{0}.cshtml", "~/Themes/{2}/Views/Shared/{0}.cshtml", //default "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml", //Admin //"~/Administration/Views/{1}/{0}.cshtml", //"~/Administration/Views/Shared/{0}.cshtml", }; MasterLocationFormats = new[] { //themes "~/Themes/{2}/Views/{1}/{0}.cshtml", "~/Themes/{2}/Views/Shared/{0}.cshtml", //default "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml" }; PartialViewLocationFormats = new[] { //themes "~/Themes/{2}/Views/{1}/{0}.cshtml", "~/Themes/{2}/Views/Shared/{0}.cshtml", //default "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml", //Admin //"~/Administration/Views/{1}/{0}.cshtml", //"~/Administration/Views/Shared/{0}.cshtml", }; FileExtensions = new[] { "cshtml" }; }