ASP.NET Razor 视图引擎编程参考
ASP.NET Razor 视图引擎编程参考
转载请注明出处:http://surfsky.cnblogs.com
Rasor 视图引擎
http://msdn.microsoft.com/zh-cn/library/ff849693.aspx
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=b7937c34-3b53-47b7-ae17-5a72fa700472&displaylang=en
http://aspnet.codeplex.com/wikipage?title=WebPages&referringTitle=Home
优点:“干练简单”
可以用它来做MVC视图引擎,也可以直接用它来编写传统类似php式的网站,非常轻便。
语法识别
嵌入变量
<h3>Hello @name, the year is @DateTime.Now.Year </h3>
<a href="/products/details/@productId">the product</a>
表达式(括号)
<p>Your message : @("Number is: " + number) </p>
代码块(花括弧)
@{
int number = 1;
string message = "Number is " + number;
}
@{ var myQuote = @"The person said: ""Hello, today is Monday."""; }
<text>标签
if (i > 0) {
<text>;</text>
}
智能区别@
<p>mail scottgu@microsoft.com telling : @Date.Now.</p>
可以显式地打@@来用另外一个”@”字符进行转义
判断
@if(products.Count == 0){
<p>Sorry - no products in this category </p>
}else{
<p>We have a products for you!</p>
}
@if (DateTime.Now.Year == 2010){
<span>
the date: @DateTime.Now
</span>
}
循环
<ul id="products">
@foreach(var p in products){
<li>@p.Name ($@p.Price) </li>
}
</ul>
模板
<!DOCTYPE html>
<html>
<body>
<div>@RenderSection("menu", optional:true)</div>
<div>@RenderBody()</div>
<div>@RenderSection("footer", optional:true)</div>
</body>
</html>
-----------------------------
@{LayoutPage = "sitelayout.cshtml";}
<p>current datetime: @DateTime.Now</p>
@section menu{
<ul id="sub-menu">
<li>item1</li>
<li>item2</li>
</ul>
}
@section footer{
<p>this is my custom footer</p>
}
辅助函数
@Html.LabelFor(m => m.ProductID)
@Html.TextBoxFor(m => m.ProductID)
@Html.ValidationMessageFor(m => m.ProductID)
创建辅助函数
@helper ProductListing(List<Product> products){
<ul>
@foreach(var p in products){
<li>@p.Name ($@p.Price)</li>
}
</ul>
}
<div>@ProductListing(Model.Products)</div>
函数参数
<h1>small bakery products</h1>
@Grid.Render(
data: Model.products,
tableStyle: "grid",
headerStyle: "head",
alternationRowStyle: "alt",
columns: Grid.Columns(
Grid.Column("Name", "Product", style:"Product"),
Grid.Column("Description", format:@(<i>@item.Description</i>),
Grid.Column("Price", format:@<span>$@item.Price</span>)
)
)
函数
@using System.Text;
@functions {
public static IHtmlString Repeat(int times, Func<int, object> template) {
StringBuilder builder = new StringBuilder();
for(int i = 0; i < times; i++) {
builder.Append(template(i));
}
return new HtmlString(builder.ToString());
}
}
@Repeat(10, @<li>List Item</li>);
@Repeat(10, @<li>List Item #@item</li>);
类型转换
var myStringNum = "539";
var myStringBool = "True";
var myStringFloat = "41.432895";
var myStringDec = "10317.425";
var myDateString = "12/27/2010";
-------------------------------
if(myStringNum.IsInt()==true)
var myIntNumber = myStringNum.AsInt();
var myVar = myStringBool.AsBool();
var myFloatNum = myStringFloat.AsFloat();
var myDecNum = myStringDec.AsDecimal();
var newDate = myDateString.AsDateTime();
文件
访问cshtml文件均无需加扩展名。如:~/Gallery/Index
下划线开始的cshtml文件不能单独运行(一般是做为模板文件、公共控件)
几个特殊文件
_init.cshtml
@{
// Set the layout page for the whole site
LayoutPage = "_Master.cshtml";
}
_start.cshtml
@{
WebSecurity.InitializeDatabaseConnection("PhotoGallery", "UserProfiles", "UserId", "Email", true);
}
--------------------------------
-- more
--------------------------------
@Inherits System.Web.Mvc.WebViewPage
View.Title = "Home Page";
LayoutPage = "~/Views/Shared/_layout.cshtml";
View.Message
Login
check
if (WebSecurity.IsAuthenticated){
欢迎您,<b>@WebSecurity.CurrentUserName</b>!
@Html.ActionLink("注销", "LogOff", "Account")
}
else{
@Html.ActionLink("登录", "LogOn", "Account")
}
@if (WebSecurity.IsAuthenticated) {
<span>Welcome <b><a href="@Href("~/Account/ChangePassword")">@WebSecurity.CurrentUserName</a></b>!
[ <a href="@Href("~/Account/Logout")">Logout</a> ]</span>
} else {
<span>[ <a href="@Href("~/Account/Login")">Login</a> | <a href="@Href("~/Account/Register")">Register</a> ]</span>
}
login
// Attempt to login to the Security object using provided creds
if (WebSecurity.Login(username, password, rememberMe)) {
Response.Redirect("~/");
}
logout
WebSecurity.Logout();
regist
WebSecurity.CreateAccount(email, password, requireEmailConfirmation)
WebSecurity.ConfirmAccount(confirmationToken)
WebSecurity.GetUserId(email)
WebSecurity.GeneratePasswordResetToken(email)
password
WebSecurity.ResetPassword(passwordResetToken, newPassword)
WebSecurity.ChangePassword(WebSecurity.CurrentUserName, currentPassword, newPassword)
Template
@RenderPage("/Shared/_Header.cshtml")
@RenderPage("/Shared/_Footer.cshtml")
@RenderBody()
@RenderSection("fffff")
microsoft sql server compact edition
var db = Database.OpenFile("database.sdf");
var sql = "select * from table1";
var data = db.Query(sql);
Database.Execute(sql)
fileupload
@FileUpload.GetHtml(
initialNumberOfFiles: 1,
allowMoreFilesToBeAdded: false,
includeFormTag: true,
uploadText: "Upload"
)
Image
WebImage.Resize();
WebImage.FlipVertical();
.FlipHorizontal();
.FlipLeft();
.FlipRight();
WebImage.AddTextWatermark();
WebImage.AddImageWatermark();
Video
@Video.Flash(
path: "testFlash.swf",
width: "400",
height: "600",
play: true,
loop: true;
menu: false,
bgColor: "red",
quality: "medium",
scale: "exactfit",
windowMode: "transparent"
);
@Video.MediaPlayer()
@Video.Silverlight()
Toolkit(Microsoft.WebPages.Helpers.Toolkit.dll)
Twitter
@Twitter.Profile("haacked")
Facebook
Gravator
Recaptcha
Form Postback
<form action="" method="post">
<p>
<label for="text1">First Number:</label>
<input type="text" name="text1" />
</p>
<p>
<label for="text2">Second Number:</label>
<input type="text" name="text2" />
</p>
<p><input type="submit" value="Add" /></p>
</form>
<p>@totalMessage</p>
@{
var totalMessage = "";
if(IsPost) {
var num1 = Request["text1"];
var num2 = Request["text2"];
var total = num1.AsInt() + num2.AsInt();
totalMessage = "Total = " + total;
}
}
mail
Mail.Send(
to: email,
subject: "Please reset your password",
body: "Use this password reset token to reset your password. The token is: " + resetToken + @". Visit <a href=""" + resetUrl + @""">" + resetUrl + "</a> to reset your password."
);
Mail.SmtpServer.IsEmpty()
--------------------------------
-- 可用的 MVC 辅助函数和辅助类
--------------------------------
@Inherits System.Web.Mvc.WebViewPage
@Inherits System.Web.Mvc.WebViewPage<IList<RasorSample.Models.Category>>
@model LIst<Product>
@PageData["Title"] 用于页面内数据共享,如masterpage和contentpage共享
@Href("~/Site.css") 获取url
@WebSecurity 封装了用户安全相关函数
@UrlData[0] 应该等效于Request["..."]
@Html.PageLink("View", (string)similarTags[i].TagName, (string)similarTags[i].TagName)
<a href="@HrefAttribute("View", tag.TagName)">
转载请注明出处:http://surfsky.cnblogs.com
ASP.NET Razor 视图引擎编程参考的更多相关文章
- ASP.Net MVC开发基础学习笔记:三、Razor视图引擎、控制器与路由机制学习
一.天降神器“剃须刀” — Razor视图引擎 1.1 千呼万唤始出来的MVC3.0 在MVC3.0版本的时候,微软终于引入了第二种模板引擎:Razor.在这之前,我们一直在使用WebForm时代沿留 ...
- Razor 视图引擎 – ASP.NET MVC 4 系列
Razor 视图引擎是 ASP.NET MVC 3 开始扩展的内容,并且也是默认视图引擎. Razor 通过理解标记的结构来实现代码和标记之间尽可能顺畅的转换.下面的例子演 ...
- ASP.Net MVC开发基础学习笔记(3):Razor视图引擎、控制器与路由机制学习
一.天降神器“剃须刀” — Razor视图引擎 1.1 千呼万唤始出来的MVC3.0 在MVC3.0版本的时候,微软终于引入了第二种模板引擎:Razor.在这之前,我们一直在使用WebForm时代沿留 ...
- Asp.Net Mvc视图引擎Razor介绍
1.Razor介绍 1)ASP.NET MVC3 带来了一种新的名为Razor 的视图引擎,提供了下列优点: Razor 的语法简单且清晰,只需要最小化的输入 Razor 容易学习,语法类似于 C# ...
- ASP.NET MVC Razor视图引擎攻略
--引子 看下面一段MVC 2.0的代码. <%if (Model != null){%> <p><%=Model%></p><%}%>&l ...
- ASP.NET MVC 3 Razor 视图引擎 基本语法
本篇博文将进入MVC 3 的世界了,首先学习一下MVC 3 新增的Razor视图引擎的基本语法. 1. 使用 @ 字符将代码添加到页面中.正如传统的aspx视图的<% %>相同. ...
- ASP.NET MVC3 系列教程 - Razor视图引擎基础语法
http://www.cnblogs.com/highend/archive/2011/04/09/aspnet_mvc3_razor_engine.html 4. 关于所有带"_" ...
- ASP.NET MVC3 Razor视图引擎-基础语法
I:ASP.NET MVC3在Visual Studio 2010中的变化 在VS2010中新建一个MVC3项目可以看出与以往的MVC2发生了很明显的变化. 1.ASP.NET MVC3必要的运行环境 ...
- ASP.Net MVC(3) 之Razor视图引擎的基础语法
Razor视图引擎的基础语法: 1.“_”开头的cshtml文档将不能在服务器上访问,和asp.net中的config文档差不多. 2.Razor语法以@开头,以@{}进行包裹. 3.语法使用: 注释 ...
随机推荐
- iOS 数字字符串的直接运算 + - * /
NSDecimalNumber *d1 = [NSDecimalNumber decimalNumberWithString:@"3.14"]; NSDecimalNumber * ...
- Undefined symbols for architecture x86_64 解决之道
目前临时的解决办法是 1.把1.选中Targets—>Build Settings—>Architectures. 把build active architectures only 改为 ...
- Valid Number @python
Valid Number Validate if a given string is numeric. Some examples:"0" => true" 0.1 ...
- Ubuntu设置环境变量并立即生效
Ubuntu Linux系统包含两类环境变量:系统环境变量和用户环境变量.系统环境变量对所有系统用户都有效,用户环境变量仅仅对当前的用户有效. 修改用户环境变量 用户环境变量通常被存储在下面的文件中: ...
- C++学习14 继承的概念及语法
继承是类与类之间的关系,是一个很简单很直观的概念,与现实世界中的继承(例如儿子继承父亲财产)类似. 继承(Inheritance)可以理解为一个类从另一个类获取成员变量和成员函数的过程.例如类B继承于 ...
- 我自己做的网站终于上线啦,用tornado做的,求围观 www.yustock.live
跟股票相关的一个小网站~ www.yustock.live
- java类的高级特性
1.非内部类不能被声明为private 或protected访问类型.
- 在解决方案中所使用 NuGet 管理软件包依赖
使用程序包恢复功能可以在提交源代码时, 不需要将代码库提交到源代码管理中,大幅减少项目的尺寸.所有NuGet程序包都存储在解决方案的Packages文件夹中. 要启用程序包恢复功能,可右键单击解决方案 ...
- Appnium安装——Mac篇
mac下搭建appium环境有两种方法: 1.直接下载appium.dmg 运行即可 2.使用node从命令行运行appium Mac下的appnium环境搭建 一.首先安装homebrew 1.首先 ...
- Android开发-API指南-Bound 类型的服务
Bound Services 英文原文:http://developer.android.com/guide/components/bound-services.html 采集(更新)日期:2014- ...