ASP.NET Web Pages (Razor) API Quick Reference
This page contains a list with brief examples of the most commonly used objects, properties, and methods for programming ASP.NET Web Pages with Razor syntax.
Descriptions marked with "(v2)" were introduced in ASP.NET Web Pages version 2.
For API reference documentation, see the ASP.NET Web Pages Reference Documentation on MSDN.
Software versions
This page contains reference information for the following:
Classes
|
Contains data that can be shared by any pages in the application. You can use the dynamic AppState["FavoriteColor"] = "red"; |
|
Converts a string value to a Boolean value (true/false). Returns false or the specified value if the string does not represent true/false. bool b = stringValue.AsBool(); |
|
Converts a string value to date/time. Returns DateTime dt = stringValue.AsDateTime(); |
|
Converts a string value to a decimal value. Returns 0.0 or the specified value if the string does not represent a decimal value. decimal d = stringValue.AsDecimal(); |
|
Converts a string value to a float. Returns 0.0 or the specified value if the string does not represent a decimal value. float d = stringValue.AsFloat(); |
|
Converts a string value to an integer. Returns 0 or the specified value if the string does not represent an integer. int i = stringValue.AsInt(); |
|
Creates a browser-compatible URL from a local file path, with optional additional path parts. <a href="@Href("~/Folder/File")">Link to My File</a>
|
|
Renders value as HTML markup instead of rendering it as HTML-encoded output. @* Inserts markup into the page. *@ |
|
Returns true if the value can be converted from a string to the specified type. var isint = stringValue.IsInt(); |
|
Returns true if the object or variable has no value. if (Request["companyname"].IsEmpty()) {
|
|
Returns true if the request is a POST. (Initial requests are usually a GET.) if (IsPost) { Response.Redirect("Posted"); }
|
|
Specifies the path of a layout page to apply to this page. Layout = "_MyLayout.cshtml"; |
|
Contains data shared between the page, layout pages, and partial pages in the current request. You can use the dynamic PageData["FavoriteColor"] = "red"; |
|
(Layout pages) Renders the content of a content page that is not in any named sections. @RenderBody() |
|
Renders a content page using the specified path and optional extra data. RenderPage("_MySubPage.cshtml", "red", 123, "apples")
|
|
(Layout pages) Renders a content section that has a name. Set required to false to make a section optional. @RenderSection("header")
|
|
Gets or sets the value of an HTTP cookie. var cookieValue = Request.Cookies["myCookie"].Value; |
|
Gets the files that were uploaded in the current request. Request.Files["postedFile"].SaveAs(@"MyPostedFile"); |
|
Gets data that was posted in a form (as strings). var formValue = Request.Form["myTextBox"]; |
|
Gets data that was specified in the URL query string. var queryValue = Request.QueryString["myTextBox"]; |
|
Selectively disables request validation for a form element, // Call the method directly to disable validation on the specified item from |
|
Adds an HTTP server header to the response. // Adds a header that requests client browsers to use basic authentication. |
|
Caches the page output for a specified time. Optionally set sliding to reset the timeout on each page access and varyByParams to cache different versions of the page for each different query string in the page request. Response.OutputCache(60); |
|
Redirects the browser request to a new location. Response.Redirect("~/Folder/File");
|
|
Sets the HTTP status code sent to the browser. Response.SetStatus(HttpStatusCode.Unauthorized); |
|
Writes the contents of data to the response with an optional MIME type. Response.WriteBinary(image, "image/jpeg"); |
|
Writes the contents of a file to the response. Response.WriteFile("file.ext");
|
|
(Layout pages) Defines a content section that has a name. @section header { <div>Header text</div> }
|
|
Decodes a string that is HTML encoded. var htmlDecoded = Server.HtmlDecode("<html>");
|
|
Encodes a string for rendering in HTML markup. var htmlEncoded = Server.HtmlEncode("<html>");
|
|
Returns the server physical path for the specified virtual path. var dataFile = Server.MapPath("~/App_Data/data.txt");
|
|
Decodes text from a URL. var urlDecoded = Server.UrlDecode("url%20data");
|
|
Encodes text to put in a URL. var urlEncoded = Server.UrlEncode("url data");
|
|
Gets or sets a value that exists until the user closes the browser. Session["FavoriteColor"] = "red"; |
|
Displays a string representation of the object's value. <p>It is now @DateTime.Now.ToString()</p> |
|
Gets additional data from the URL (for example, /MyPage/ExtraData). var pathInfo = UrlData[0]; |
|
Changes the password for the specified user. var success = WebSecurity.ChangePassword("my-username",
|
|
Confirms an account using the account confirmation token. var confirmationToken = Request.QueryString["ConfirmationToken"]; |
|
Creates a new user account with the specified user name and password. To require a confirmation token, WebSecurity.CreateAccount("my-username", "secretpassword");
|
|
Gets the integer identifier for the currently logged-in user. var userId = WebSecurity.CurrentUserId; |
|
Gets the name for the currently logged-in user. var welcome = "Hello " + WebSecurity.CurrentUserName; |
|
Generates a password-reset token that can be sent in email to a user so that the var resetToken = WebSecurity.GeneratePasswordResetToken("my-username");
|
|
Returns the user ID from the user name. var userId = WebSecurity.GetUserId(userName); |
|
Returns true if the current user is logged in. if(WebSecurity.IsAuthenticated) {...}
|
|
Returns true if the user has been confirmed (for example, through a confirmation email). if(WebSecurity.IsConfirmed("joe@contoso.com")) { ... }
|
|
Returns true if the current user’s name matches the specified user name. if(WebSecurity.IsCurrentUser("joe@contoso.com")) { ... }
|
|
Logs the user in by setting an authentication token in the cookie. if(WebSecurity.Login("username", "password")) { ... }
|
|
Logs the user out by removing the authentication token cookie. WebSecurity.Logout(); |
|
If the user is not authenticated, sets the HTTP status to 401 (Unauthorized). WebSecurity.RequireAuthenticatedUser(); |
|
If the current user is not a member of one of the specified roles, sets the HTTP status to 401 (Unauthorized). WebSecurity.RequireRoles("Admin", "Power Users");
|
|
If the current user is not the user specified by WebSecurity.RequireUser("joe@contoso.com");
|
|
If the password reset token is valid, changes the user’s password to the new password. WebSecurity.ResetPassword( "A0F36BFD9313", "new-password") |
Data
|
Executes SQLstatement (with optional parameters) such as INSERT, DELETE, or UPDATE and returns a count of affected records. db.Execute("INSERT INTO Data (Name) VALUES ('Smith')");
db.Execute("INSERT INTO Data (Name) VALUES (@0)", "Smith");
|
|
Returns the identity column from the most recently inserted row. db.Execute("INSERT INTO Data (Name) VALUES ('Smith')");
|
|
Opens either the specified database file or the database specified using // Note that no filename extension is specified. |
|
Opens a database using the connection string. (This contrasts with var db = Database.OpenConnectionString("Data Source=|DataDirectory|\SmallBakery.sdf");
|
|
Queries the database using SQLstatement (optionally passing parameters) and returns the results as a collection. foreach (var result in db.Query("SELECT * FROM PRODUCT")) {<p>@result.Name</p>}
foreach (var result = db.Query("SELECT * FROM PRODUCT WHERE Price > @0", 20))
|
|
Executes SQLstatement (with optional parameters) and returns a single record. var product = db.QuerySingle("SELECT * FROM Product WHERE Id = 1");
var product = db.QuerySingle("SELECT * FROM Product WHERE Id = @0", 1);
|
|
Executes SQLstatement (with optional parameters) and returns a single value. var count = db.QueryValue("SELECT COUNT(*) FROM Product");
var count = db.QueryValue("SELECT COUNT(*) FROM Product WHERE Price > @0", 20);
|
Helpers
|
Renders the Google Analytics JavaScript code for the specified ID. @Analytics.GetGoogleHtml("MyWebPropertyId")
|
|
Renders the StatCounter Analytics JavaScript code for the specified project. @Analytics.GetStatCounterHtml(89, "security") |
|
Renders the Yahoo Analytics JavaScript code for the specified account. @Analytics.GetYahooHtml("myaccount")
|
|
Passes a search to Bing. To specify the site to search and a title for the search box, you can set the @Bing.SearchBox() @* Searches the web.*@ @{
|
|
Initializes a chart. @{
|
|
Adds a legend to a chart. @{
|
|
Adds a series of values to the chart. @{
|
|
Returns a hash for the specified data. The default algorithm is @Crypto.Hash("data")
|
|
Lets Facebook users make a connection to pages. @Facebook.LikeButton("www.asp.net")
|
|
Renders UI for uploading files. @FileUpload.GetHtml(initialNumberOfFiles:1, allowMoreFilesToBeAdded:false, |
|
Renders the specified Xbox gamer tag. @GamerCard.GetHtml("joe")
|
|
Renders the Gravatar image for the specified email address. @Gravatar.GetHtml("joe@contoso.com")
|
|
Converts a data object to a string in the JavaScript Object Notation (JSON) format. var myJsonString = Json.Encode(dataObject); |
|
Converts a JSON-encoded input string to a data object that you can iterate over or insert into a database. var myJsonObj = Json.Decode(jsonString); |
|
Renders social networking links using the specified title and optional URL. @LinkShare.GetHtml("ASP.NET Web Pages Samples")
|
|
Associates an error message with a form field. Use the ModelState.AddError("email", "Enter an email address");
|
|
Associates an error message with a form. Use the ModelState.AddFormError("Password and confirmation password do not match.");
|
|
Returns true if there are no validation errors. Use the if (ModelState.IsValid) { // Save the form to the database }
|
|
Renders the properties and values of an object and any child objects. @ObjectInfo.Print(person) |
|
Renders the reCAPTCHA verification test. @ReCaptcha.GetHtml() |
|
Sets public and private keys for the reCAPTCHA service. Normally you set ReCaptcha.PublicKey = "your-public-recaptcha-key"; |
|
Returns the result of the reCAPTCHA test. if (ReCaptcha.Validate()) {
|
|
Renders status information about ASP.NET Web Pages. @ServerInfo.GetHtml() |
|
Renders a Twitter stream for the specified user. @Twitter.Profile("billgates")
|
|
Renders a Twitter stream for the specified search text. @Twitter.Search("asp.net")
|
|
Renders a Flash video player for the specified file with optional width and height. @Video.Flash("test.swf", "100", "100")
|
|
Renders a Windows Media player for the specified file with optional width and height. @Video.MediaPlayer("test.wmv", "100", "100")
|
|
Renders a Silverlight player for the specified .xap file with required width and height. @Video.Silverlight("test.xap", "100", "100")
|
|
Returns the object specified by key, or null if the object is not found. var username = WebCache.Get("username")
|
|
Removes the object specified by key from the cache. WebCache.Remove("username")
|
|
Puts value into the cache under the name specified by key. WebCache.Set("username", "joe@contoso.com ")
|
|
Creates a new var db = Database.Open("SmallBakery");
|
|
Renders markup to display data in an HTML table. @grid.GetHtml()// The 'grid' variable is set when WebGrid is created. |
|
Renders a pager for the @grid.Pager() // The 'grid' variable is set when WebGrid is created. |
|
Loads an image from the specified path. var image = new WebImage("test.png");
|
|
Adds the specified image as a watermark. WebImage photo = new WebImage("test.png");
|
|
Adds the specified text to the image. image.AddTextWatermark("Copyright")
|
|
Flips the image horizontally or vertically. image.FlipHorizontal(); |
|
Loads an image when an image is posted to a page during a file upload. var image = WebImage.GetImageFromRequest(); |
|
Resizes an the image. image.Resize(100, 100); |
|
Rotates the image to the left or the right. image.RotateLeft(); |
|
Saves the image to the specified path. image.Save("test.png");
|
|
Sets the password for the SMTP server. Normally you set this property in the _AppStart page. WebMail.Password = "password"; |
|
Sends an email message. WebMail.Send("touser@contoso.com", "subject", "body of message",
|
|
Sets the SMTP server name. Normally you set this property in the _AppStart page. WebMail.SmtpServer = "smtp.mailserver.com"; |
|
Sets the user name for the SMTP server. Normally you should set this property in the _AppStart page. WebMail.UserName = "Joe"; |
Validation
|
(v2) Renders a validation error message for the specified field. <input type="text" |
|
(v2) Displays a list of all validation errors. @Html.ValidationSummary()
@Html.ValidationSummary("The following validation errors occurred:")
|
|
(v2) Registers a user input element for the specified type of validation. Validation.Add("dateOfBirth", Validator.DateTime("Date of birth was not valid"));
|
|
(v2) Dynamically renders CSS class attributes for client-side validation so that you can format validation error messages. (Requires that you reference the appropriate client-script libraries and that you define CSS classes.) <head> |
|
(v2) Enables client-side validation for the user input field. (Requires that you reference the appropriate client-script libraries.) <head> |
|
(v2) Returns true if all user input elements that are registred for validation contain valid values. if(IsPost){
|
|
(v2) Specifies that users must provide a value for the user input element. Validation.RequireField("dateOfBirth", "Date of birth is required");
|
|
(v2) Specifies that users must provide values for each of the user input elements. This method does not let you specify a custom error message. Validation.RequireFields("firstName", "lastName", "dateOfBirth");
|
|
(v2) Validation.Add("dateOfBirth", Validator.DateTime("Date of birth was not valid"));
|
This article was originally created on February 10, 2014
Author Information
Tom FitzMacken – Tom FitzMacken is a Senior Programming Writer on the Web Platform & Tools Content team.
ASP.NET Web Pages (Razor) API Quick Reference的更多相关文章
- Displaying Data in a Chart with ASP.NET Web Pages (Razor)
This article explains how to use a chart to display data in an ASP.NET Web Pages (Razor) website by ...
- 如何在ASP.NET Web站点中统一页面布局[Creating a Consistent Layout in ASP.NET Web Pages(Razor) Sites]
如何在ASP.NET Web站点中统一页面布局[Creating a Consistent Layout in ASP.NET Web Pages(Razor) Sites] 一.布局页面介绍[Abo ...
- Customizing Site-Wide Behavior for ASP.NET Web Pages (Razor) Sites
Customizing Site-Wide Behavior for ASP.NET Web Pages (Razor) Sites By Tom FitzMacken|February 17, 20 ...
- ASP.NET Web Pages (Razor) FAQ
ASP.NET Web Pages (Razor) FAQ By Tom FitzMacken|February 7, 2014 Print This article lists some fre ...
- Announcing the Release of ASP.NET MVC 5.1, ASP.NET Web API 2.1 and ASP.NET Web Pages 3.1 for VS2012
The NuGet packages for ASP.NET MVC 5.1, ASP.NET Web API 2.1 and ASP.NET Web Pages 3.1 are now live o ...
- ASP.NET Web Pages:Razor
ylbtech-.Net-ASP.NET Web Pages:Razor 1.返回顶部 1. ASP.NET Web Pages - 添加 Razor 代码 在本教程中,我们将使用 C# 和 Visu ...
- Transferring Data Between ASP.NET Web Pages
14 July 2012 20:24 http://www.mikesdotnetting.com/article/192/transferring-data-between-asp-net-web- ...
- Web Pages razor 学习
1. Web Pages razor Web Pages 是三种 ASP.NET 编程模型中的一种,用于创建 ASP.NET 网站和 web 应用程序. 其他两种编程模型是 Web Forms 和 M ...
- ASP.NET Web Pages 的冲突版本问题
随着VS版本和.NET MVC版本.EF的版本的不断更新,虽然很多功能随着版本的提升而更完善,但对于旧版本开发的软件就有点悲催了,或许很多开发者都遇到类似的问题! 最近有一个项目是用.NET MVC3 ...
随机推荐
- cxLookupCombobox的多字段模糊匹配
查了网上很多资料,懒人输入:通过程序使用过滤对话达到自己的目的: 用到cxFilter单元: cbb_DoctorOrder.Properties.View.DataController.Filter ...
- css position是前端的你了解多少?
此文根据Steven Bradley的<How Well Do You Understand CSS Positioning?>所译,整个译文带有我自己的理解与思想,如果译得不好或不对之处 ...
- ajax传递参数给springmvc
下面看一些传参的例子,基本涵盖了大部分的参数传递类型
- python018 Python3 输入和输出
Python3 输入和输出在前面几个章节中,我们其实已经接触了 Python 的输入输出的功能.本章节我们将具体介绍 Python 的输入输出. 输出格式美化Python两种输出值的方式: 表达式语句 ...
- POJ 3615 Cow Hurdles
http://poj.org/problem?id=3615 floyd 最短路径的变形 dist[i][j]变化为 : i j之间的最大边 那么输入的时候可以直接把dist[i][j] 当作i j ...
- 2016 Multi-University Training Contest 7 solutions BY SYSU
Ants 首先求出每个点的最近点. 可以直接对所有点构造kd树,然后在kd树上查询除本身以外的最近点,因为对所有点都求一次,所以不用担心退化. 也可以用分治做,同样是O(NlogN)的复杂度. 方法是 ...
- 2017"百度之星"程序设计大赛 - 初赛(B)度度熊的交易计划
n个村庄m条带权路,权值为花费,村庄可以造东西卖东西,造完东西可以换地方卖,给出每个村庄造东西花费a和最多个数b.卖东西价值c和最多个数d,求最大收益. 裸的费用流.然而还WA了一发.很好. 建源向每 ...
- hihoCoder #1014 : Trie树 [ Trie ]
传送门 #1014 : Trie树 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi和小Ho是一对好朋友,出生在信息化社会的他们对编程产生了莫大的兴趣,他们约定好互 ...
- transient 关键字
java语言的关键字,变量修饰符,如果用transient声明一个实例变量,当对象存储时,它的值不需要维持.换句话来说就是,用transient关键字标记的成员变量不参与序列化过程. 作用 Jav ...
- Pick-up sticks--poj2653(判断两线段是否相交)
http://poj.org/problem?id=2653 题目大意:有n根各种长度的棍 一同洒在地上 求在最上面的棍子有那几个 分析: 我刚开始想倒着遍历 因为n是100000 想着会 ...