




已阅读5页,还剩29页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
A MVC Razor中文文档 1. 符号增加代码 var total = 7; var myMessage = Hello World; The value of your account is: total The value of myMessage is: myMessage var greeting = Welcome to our site!; var weekDay = DateTime.Now.DayOfWeek; var greetingMessage = greeting + Today is: + weekDay;The greeting is: greetingMessage运行后这样子:HTML编码符号默认的使用Html编码, 将 HTML 字符 (如,&) 进行了相应的转码。2. 使用大括号 var theMonth = DateTime.Now.Month; The numeric value of the current month: theMonth var outsideTemp = 79; var weatherMessage = Hello, it is + outsideTemp + degrees.;Todays weather: weatherMessage结果:3. 在一个代码块中,使用分号分隔每一条语句。 var theMonth = DateTime.Now.Month; var outsideTemp = 79; var weatherMessage = Hello, it is + outsideTemp + degrees.;Todays weather: weatherMessage4. 使用变量使用变量 包含strings, numbers, and dates, etc. 创建变量使用var关键字. 使用变量使用. var welcomeMessage = Welcome, new members!; welcomeMessage var year = DateTime.Now.Year; Welcome to our new members who joined in year!结果:5. 表示字符串,使用双引号。 var myString = This is a string literal; 如果字符串中包含,或双引号,使用作前缀 var myFilePath = C:MyFolder; The path is: myFilePath包含双引号 var myQuote = The person said: Hello, today is Monday.; myQuote结果:6. 代码是大小写敏感的以下是两个不同的变量. var lastName = Smith; var LastName = Jones;Note Visual Basic, 关键字不区分大小写.7. 对象处理 Requested URL Relative Path Full Path HTTP Request Type Request.Url Request.FilePath Request.MapPath(Request.FilePath) Request.RequestType结果:8. 条件语句 var result = ; if(IsPost) result = This page was posted using the Submit button.; else result = This was the first request for this page.; result 结果:简单例子 var total = 0; var totalMessage = ; if(IsPost) / Retrieve the numbers that the user entered. var num1 = Requesttext1; var num2 = Requesttext2; / Convert the entered strings into integers numbers and add. total = num1.AsInt() + num2.AsInt(); totalMessage = Total = + total; Add Numbers body background-color: beige; font-family: Verdana, Arial; margin: 50px; form padding: 10px; border-style: solid; width: 250px; Enter two whole numbers and then click Add. First Number: Second Number: totalMessage基础概念The Razor Syntax, Server Code, and ASP.NETRazor syntax有一个特别的文件扩展名(.cshtmlor.vbhtml).基本语法文本, 标记, 代码 文本包含在html元素中如或:if(IsPost) / This line has all content between matched tags. Hello, the time is DateTime.Now and this page is a postback! else / All content between matched tags, followed by server code. Hello stranger, today is: DateTime.Now 使用:操作符或标记.:输出一行,或无匹配的html; 可以输出多行. if(IsPost) / Plain text followed by an unmatched HTML tag and server code. : The time is: DateTime.Now / Server code and then plain text, matched tags, and more text. DateTime.Now :is the current time.if(IsPost) / Repeat the previous example, but use tags. The time is: DateTime.Now DateTime.Now is the current time. var minTemp = 75; It is the month of DateTime.Now.ToString(MMMM), and its a great day! You can go swimming if its at least minTemp degrees. 注意:或并没有html编码空格有效 var lastName = Smith; var theName =Smith; var personName = Smith ; 无效: var test = This is a long string; / Does not work!使用,有效: var longString = This is a long string;注释使用*开始*结束. * A one-line code comment. * This is a multiline code comment. It can continue for any number of lines.* * This is a comment. * var theVar = 17; * This is a comment. * * var theVar = 17; * 在代码内部可以使用语言的注释语法: / This is a comment. var myVar = 17; /* This is a multi-line comment that uses C# commenting syntax. */Html注释:!- This is my paragraph. -变量和数据类型使用var或类型的名字: / Assigning a string to a variable. var greeting = Welcome!; / Assigning a number to a variable. var theCount = 3; / Assigning an expression to a variable. var monthlyTotal = theCount + 5; / Assigning a date value to a variable. var today = DateTime.Today; / Assigning the current pages URL to a variable. var myPath = this.Request.Url; / Declaring variables using explicit data types. string name = Joe; int count = 5; DateTime tomorrow = DateTime.Now.AddDays(1);一些典型使用: / Embedding the value of a variable into HTML markup. greeting, friends! / Using variables as part of an inline expression. The predicted annual total is: ( monthlyTotal * 12) / Displaying the page URL with a variable. The URL to this page is: myPath结果:转换和测试数据类型转换字符串到int. var total = 0; if(IsPost) / Retrieve the numbers that the user entered. var num1 = Requesttext1; var num2 = Requesttext2; / Convert the entered strings into integers numbers and add. total = num1.AsInt() + num2.AsInt(); 使用AsInt方法.下面是一些常用的方法转换列表:.方法描述例子AsInt(),IsInt()String转为 intvar myIntNumber = 0;var myStringNum = 539;if(myStringNum.IsInt()=true) myIntNumber = myStringNum.AsInt();AsBool(),IsBool()String转为Boolean类型var myStringBool = True;var myVar = myStringBool.AsBool();AsFloat(),IsFloat()转为float类型var myStringFloat = 41.432895;var myFloatNum = myStringFloat.AsFloat(); AsDecimal(),IsDecimal()转为decimal类型var myStringDec = 10317.425;var myDecNum = myStringDec.AsDecimal(); AsDateTime(),IsDateTime()转为DateTime类型var myDateString = 12/27/2010;var newDate = myDateString.AsDateTime(); ToString()其它类型转为字符串int num1 = 17;int num2 = 76;/ myString is set to 1776string myString = num1.ToString() + num2.ToString();操作符.OperatorDescriptionExamples+-*/数字操作(5 + 13) var netWorth = 150000; var newTotal = netWorth * 2; (newTotal / 2)=赋值.var age = 17;=相等var myNum = 15;if (myNum = 15) / Do something. !=不等.var theNum = 13;if (theNum != 15) / Do something.=小于,大小,小于等于,大于等于if (2 = 12) / Do something.+连接符,基于数据类型./ The displayed result is abcdef.(abc + def)+=-=加减.int theCount = 0;theCount += 1; / Adds 1 to count.对象属性或方法.var myUrl = Request.Url;var count = RequestCount.AsInt();()传参或优先级(3 + 7)Request.MapPath(Request.FilePath);indexvar income = RequestAnnualIncome;!非bool taskCompleted = false;/ Processing.if(!taskCompleted) / Continue processing&|与或bool myTaskCompleted = false;int totalCount = 0;/ Processing.if(!myTaskCompleted & totalCount 12) / Continue processing.文件或路径C:WebSitesMyWebSite default.cshtml datafile.txt images Logo.jpg styles Styles.css 物理路径h:C:WebSitesMyWebSiteFolderstylesStyles.css 虚拟路径:/styles/Styles.css 操作: 获取虚拟目录 var myImagesFolder = /images; var myStyleSheet = /styles/StyleSheet.css;Server.MapPath 方法: 得到物理路径 var dataFilePath = /dataFile.txt;Server.MapPath(dataFilePath)Href 方法:创建路径到资源Href方法可以包含 var myImagesFolder = /images; var myStyleSheet = /styles/StyleSheet.css;条件或循环测试条件 var showToday = true; if(showToday) DateTime.Today; var showToday = false; if(showToday) DateTime.Today; else Sorry! 使用else if var theBalance = 4.99; if(theBalance = 0) You have a zero balance. else if (theBalance 0 & theBalance = 5) Your balance of $theBalance is very low. else Your balance is: $theBalance 使用switch: var weekday = Wednesday; var greeting = ; switch(weekday) case Monday: greeting = Ok, its a marvelous Monday; break; case Tuesday: greeting = Its a tremendous Tuesday; break; case Wednesday: greeting = Wild Wednesday is here!; break; default: greeting = Its some other day, oh well.; break; Since it is weekday, the message for today is: greeting结果:For:for(var i = 10; i 21; i+) Line #: i.Foreach:foreach (var myItem in Request.ServerVariables) myItemwhile语句: var countNum = 0; while (countNum 50) countNum += 1; Line #countNum: Objects 和 Collections页面中常用的对象Page对象: var path = Request.FilePath; var path = this.Request.FilePath; / Access the pages Request object to retrieve the Url. var pageUrl = this.Request.Url;My page使用集合* Array block 1: Declaring a new array using braces. * Team Members string teamMembers = Matt, Joanne, Robert, Nancy; foreach (var person in teamMembers) person string teamMembers = Matt, Joanne, Robert, Nancy; The number of names in the teamMembers array: teamMembers.Length Robert is now in position: Array.IndexOf(teamMembers, Robert) The array item at position 2 (zero-based) is teamMembers2 Current order of team members in the list foreach (var name in teamMembers) name Reversed order of team members in the list Array.Reverse(teamMembers); foreach (var reversedItem in teamMembers) reversedItem 结果:使用: var myScores = new Dictionary(); myScores.Add(test1, 71); myScores.Add(test2, 82); myScores.Add(test3, 100); myScores.Add(test4, 59);My score on test 3 is: myScorestest3%(myScorestest4 = 79)My corrected score on test 4 is: myScorestest4%处理错误Try-Catch Statements var dataFilePath = /dataFile.txt; var fileContents = ; var physicalPath = Server.MapPath(dataFilePath); var userMessage = Hello world, the time is + DateTime.Now; var userErrMsg = ; var errMsg = ; if(IsPost) / When the user clicks the Open File button and posts / the page, try to open the created file for reading. try / This code fails because of faulty path to the file. fileContents = File.ReadAllText(c:batafile.txt); / This code works. To eliminate error on page, / comment the above line of code and uncomment this one. /fileContents = File.ReadAllText(physicalPath); catch (FileNotFoundException ex) / You can use the exception object for debugging, logging, etc. errMsg = ex.Message; / Create a friendly error message for users. userErrMsg = A file could not be opened, please contact + your system administrator.; catch (DirectoryNotFoundException ex) / Similar to previous exception. errMsg = ex.Message; userErrMsg = A directory was not found, please contact + your system administrator.; else / The first time the page is requested, create the text file. File.WriteAllText(physicalPath, userMessage); Try-Catch Statements fileContents userErrMsg Razor布局一列商品目录的商品URL:下面用一个简单的ProductsController实现上面的商品URL列表。它从数据库返回一列商品种类,然后传到视图文件,以在浏览器以合适的HTML响应呈示出来。下面显示Index.cshtml视图文件(用Razor来实现的)上面的视图文件没有使用布局页面这意味着我们往站点添加新的URLs和页面的时候我们会在不同的地方重复我们的核心网站布局。使用布局可以让我们避免这种重复,以后管理我们的网站设计更加容易。让我们现在更新我们的示例来使用一个吧。重构以使用布局Razor使重构现有页面以使用布局变得简单。 让我们用上面的简单示例做一下吧。 我们的第一步是往项目的视图共享文件夹(这是通用视图文件、模板所放置的地方)下添加一个“SiteLayout.cshtml”文件:SiteLayout.cshtml我们将用SiteLayout.cshtml文件来定义我们网站的通用内容, 可能看起来像下面这样:上面文件需要注意: 文件顶端不需要有一个inherits指令了。你想要的话也可以选择加上一个(比如:如果你希望有一个定制基类),但是这不是必需的。这样就能让文件美观而干净, 而且也方便程序员之外的人处理文件, 遇到他们不理解的概念也不会觉得疑惑。 我们在上面的布局文件中调用RenderBody()方法, 我们在部分的元素内输出“View.Title”属性。我还将讨论一下这是怎么使用的。现在我们有了一个通用的布局模板来保持我们网站任意页面的外观一致性。Index.cshtml我们下面根据我们刚才创建的SiteLayout.cshtml文件来更新我们的Index.cshtml视图。下面是它可能的样子的首次截图:关于上面的文件需要注意: 我们不需要将我们的主体内容包装在一个标记或元素中Razor将默认自动将Index.cshtml中的内容视为布局页面的主体部分。如果我们的布局有几个可更换的区域,我们能选择性地定义“name sections”。但是Razor让90%的情况(你只需要有一个主体部分就可以了)超级干净而简练。 上面我们编程设置了Index.cshtml页面中的View.Title的值。我们的Index.cshtml文件中的代码会比SiteLayout.cshtml中的代码先执行这样我们就能编写视图代码编程设置需要被呈示到布局的值。对像设置页面的标题,和为搜索引擎优化内的设置元素这样的事情,上面功能尤其有用。 刚才我们在Index.cshtml页面内编程设置所用的布局模板。它也可以通过设置视图上的布局属性来实现(注意:在第一个预览版中,这个属性被称为“LayoutPage”我们在ASP.NET MVC 3 Beta版中将其更名为“Layout”)。我将简单地介绍设置这个属性的几个替代方法。现在当我们在网站内请求/商品URL的时候,将得到返回如下HTML:注意上面是怎样返回一个SiteLayout.cshtml和Index.cshtml的合并HTML内容的。顶端的“Product categories”
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 外墙双排脚手架承包合同2篇
- 第八讲 劳动合同3篇
- 外币资金长期借贷协议5篇
- 产教融合校企合作人才基地框架协议(商学院)6篇
- 新解读《GB-T 31081-2014塑料箱式托盘》
- 新解读《GB-T 31163-2014太阳能资源术语》
- 农村包菜出售合同范本
- 出售土方沙子合同范本
- 公司合作签合同范本
- 医院工程建设项目管理制度汇编
- 2025至2030年中国油用牡丹行业市场分析研究及发展战略研判报告
- CJ/T 151-2016薄壁不锈钢管
- DR操作常规文档
- 四渡赤水战役解析
- 委托肉类加工合同协议
- 医学资料 TAVR手术围术期麻醉管理学习课件
- 饲料公司采购部经理述职报告
- 小米智能家居海外数据合规
- 统编教材(部编人教版)小学语文四年级上册全册教案教学设计
- 单位向个人借款标准合同文本
- 三字经全文带拼音(打印版)
评论
0/150
提交评论