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
- ASP.NET Web Pages (Razor) 3
This tutorial also works with ASP.NET Web Pages 2 and ASP.NET Web Pages 1.0 (except for features marked v2).
This page contains reference information for the following:
AppState[key], AppState[index],App
Contains data that can be shared by any pages in the application. You can use the dynamic App
property to access the same data, as in the following example:
[!code-htmlMain]
1: AppState["FavoriteColor"] = "red";
2: AppState[1] = "apples";
3: App.MyGreeting = "Good morning";
4: // Displays the value assigned to AppData[1] in the page.
5: @App[1]
6: // Displays the value assigned to App.MyGreeting.
7: @App.MyGreeting
AsBool(), AsBool(true|false)
Converts a string value to a Boolean value (true/false). Returns false or the specified value if the string does not represent true/false.
[!code-csharpMain]
1: bool b = stringValue.AsBool();
AsDateTime(), AsDateTime(value)
Converts a string value to date/time. Returns DateTime.MinValue
or the specified value if the string does not represent a date/time.
[!code-csharpMain]
1: DateTime dt = stringValue.AsDateTime();
AsDecimal(), AsDecimal(value)
Converts a string value to a decimal value. Returns 0.0 or the specified value if the string does not represent a decimal value.
[!code-csharpMain]
1: decimal d = stringValue.AsDecimal();
AsFloat(), AsFloat(value)
Converts a string value to a float. Returns 0.0 or the specified value if the string does not represent a decimal value.
[!code-csharpMain]
1: float d = stringValue.AsFloat();
AsInt(), AsInt(value)
Converts a string value to an integer. Returns 0 or the specified value if the string does not represent an integer.
[!code-csharpMain]
1: int i = stringValue.AsInt();
Href(path [, param1 [, param2]])
Creates a browser-compatible URL from a local file path, with optional additional path parts.
[!code-cshtmlMain]
1: <a href="@Href("~/Folder/File")">Link to My File</a>
2: <a href="@Href("~/Product", "Tea")">Link to Product</a>
Html.Raw(value)
Renders value as HTML markup instead of rendering it as HTML-encoded output.
[!code-cshtmlMain]
1: @* Inserts markup into the page. *@
2: @Html.Raw("<div>Hello <em>world</em>!</div>")
IsBool(), IsDateTime(), IsDecimal(), IsFloat(), IsInt()
Returns true if the value can be converted from a string to the specified type.
[!code-csharpMain]
1: var isint = stringValue.IsInt();
IsEmpty()
Returns true if the object or variable has no value.
[!code-csharpMain]
1: if (Request["companyname"].IsEmpty()) {
2: @:Company name is required.<br />
3: }
IsPost
Returns true if the request is a POST. (Initial requests are usually a GET.)
[!code-csharpMain]
1: if (IsPost) { Response.Redirect("Posted"); }
Layout
Specifies the path of a layout page to apply to this page.
[!code-htmlMain]
1: Layout = "_MyLayout.cshtml";
PageData[key], PageData[index],Page
Contains data shared between the page, layout pages, and partial pages in the current request. You can use the dynamic Page
property to access the same data, as in the following example:
[!code-htmlMain]
1: PageData["FavoriteColor"] = "red";
2: PageData[1] = "apples";
3: Page.MyGreeting = "Good morning";
4: // Displays the value assigned to PageData[1] in the page.
5: @Page[1]
6: // Displays the value assigned to Page.MyGreeting.
7: @Page.MyGreeting
RenderBody()
(Layout pages) Renders the content of a content page that is not in any named sections.
[!code-csharpMain]
1: @RenderBody()
RenderPage(path, values)
RenderPage(path[,param1 [, param2]])
Renders a content page using the specified path and optional extra data. You can get the values of the extra parameters from PageData
by position (example 1) or key (example 2).
[!code-javascriptMain]
1: RenderPage("_MySubPage.cshtml", "red", 123, "apples")
2: RenderPage("_MySubPage.cshtml", new { color = "red", number = 123, food = "apples" })
RenderSection(sectionName [, required = true|false])
(Layout pages) Renders a content section that has a name. Set required to false to make a section optional.
[!code-javascriptMain]
1: @RenderSection("header")
Request.Cookies[key]
Gets or sets the value of an HTTP cookie.
[!code-csharpMain]
1: var cookieValue = Request.Cookies["myCookie"].Value;
Request.Files[key]
Gets the files that were uploaded in the current request.
[!code-javascriptMain]
1: Request.Files["postedFile"].SaveAs(@"MyPostedFile");
Request.Form[key]
Gets data that was posted in a form (as strings). Request[key]
checks both the Request.Form
and the Request.QueryString
collections.
[!code-csharpMain]
1: var formValue = Request.Form["myTextBox"];
2: // This call produces the same result.
3: var formValue = Request["myTextBox"];
Request.QueryString[key]
Gets data that was specified in the URL query string. Request[key]
checks both the Request.Form
and the Request.QueryString
collections.
[!code-csharpMain]
1: var queryValue = Request.QueryString["myTextBox"];
2: // This call produces the same result.
3: var queryValue = Request["myTextBox"];
Request.Unvalidated(key)
Request.Unvalidated().QueryString|Form|Cookies|Headers[key]
Selectively disables request validation for a form element, query-string value, cookie, or header value. Request validation is enabled by default and prevents users from posting markup or other potentially dangerous content.
[!code-csharpMain]
1: // Call the method directly to disable validation on the specified item from
2: // one of the Request collections.
3: Request.Unvalidated("userText");
4:
5: // You can optionally specify which collection the value is from.
6: var prodID = Request.Unvalidated().QueryString["productID"];
7: var richtextValue = Request.Unvalidated().Form["richTextBox1"];
8: var cookie = Request.Unvalidated().Cookies["mostRecentVisit"];
Response.AddHeader(name, value)
Adds an HTTP server header to the response.
[!code-csharpMain]
1: // Adds a header that requests client browsers to use basic authentication.
2: Response.AddHeader("WWW-Authenticate", "BASIC");
Response.OutputCache(seconds [, sliding] [, varyByParams])
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.
[!code-javascriptMain]
1: Response.OutputCache(60);
2: Response.OutputCache(3600, true);
3: Response.OutputCache(10, varyByParams : new[] {"category","sortOrder"});
Response.Redirect(path)
Redirects the browser request to a new location.
[!code-javascriptMain]
1: Response.Redirect("~/Folder/File");
Response.SetStatus(httpStatusCode)
Sets the HTTP status code sent to the browser.
[!code-csharpMain]
1: Response.SetStatus(HttpStatusCode.Unauthorized);
2: Response.SetStatus(401);
Response.WriteBinary(data [, mimetype])
Writes the contents of data to the response with an optional MIME type.
[!code-javascriptMain]
1: Response.WriteBinary(image, "image/jpeg");
Response.WriteFile(file)
Writes the contents of a file to the response.
[!code-csharpMain]
1: Response.WriteFile("file.ext");
@section(sectionName) {content }
(Layout pages) Defines a content section that has a name.
[!code-cshtmlMain]
1: @section header { <div>Header text</div> }
Server.HtmlDecode(htmlText)
Decodes a string that is HTML encoded.
[!code-csharpMain]
1: var htmlDecoded = Server.HtmlDecode("<html>");
Server.HtmlEncode(text)
Encodes a string for rendering in HTML markup.
[!code-csharpMain]
1: var htmlEncoded = Server.HtmlEncode("<html>");
Server.MapPath(virtualPath)
Returns the server physical path for the specified virtual path.
[!code-csharpMain]
1: var dataFile = Server.MapPath("~/App_Data/data.txt");
Server.UrlDecode(urlText)
Decodes text from a URL.
[!code-csharpMain]
1: var urlDecoded = Server.UrlDecode("url%20data");
Server.UrlEncode(text)
Encodes text to put in a URL.
[!code-csharpMain]
1: var urlEncoded = Server.UrlEncode("url data");
Session[key]
Gets or sets a value that exists until the user closes the browser.
[!code-cssMain]
1: Session["FavoriteColor"] = "red";
ToString()
Displays a string representation of the object’s value.
[!code-htmlMain]
1: <p>It is now @DateTime.Now.ToString()</p>
UrlData[index]
Gets additional data from the URL (for example, /MyPage/ExtraData).
[!code-csharpMain]
1: var pathInfo = UrlData[0];
WebSecurity.ChangePassword(userName,currentPassword,newPassword)
Changes the password for the specified user.
[!code-csharpMain]
1: var success = WebSecurity.ChangePassword("my-username",
2: "current-password", "new-password");
WebSecurity.ConfirmAccount(accountConfirmationToken)
Confirms an account using the account confirmation token.
[!code-csharpMain]
1: var confirmationToken = Request.QueryString["ConfirmationToken"];
2: if(WebSecurity.ConfirmAccount(confirmationToken)) {
3: //...
4: }
WebSecurity.CreateAccount(userName, password
[, requireConfirmationToken = true|false])
Creates a new user account with the specified user name and password. To require a confirmation token, pass true for requireConfirmationToken.
[!code-csharpMain]
1: WebSecurity.CreateAccount("my-username", "secretpassword");
WebSecurity.CurrentUserId
Gets the integer identifier for the currently logged-in user.
[!code-csharpMain]
1: var userId = WebSecurity.CurrentUserId;
WebSecurity.CurrentUserName
Gets the name for the currently logged-in user.
[!code-csharpMain]
1: var welcome = "Hello " + WebSecurity.CurrentUserName;
WebSecurity.GeneratePasswordResetToken(username
[, tokenExpirationInMinutesFromNow])
Generates a password-reset token that can be sent in email to a user so that the user can reset the password.
[!code-csharpMain]
1: var resetToken = WebSecurity.GeneratePasswordResetToken("my-username");
2: var message = "Visit http://example.com/reset-password/" + resetToken +
3: " to reset your password";
4: WebMail.Send(..., message);
WebSecurity.GetUserId(userName)
Returns the user ID from the user name.
[!code-csharpMain]
1: var userId = WebSecurity.GetUserId(userName);
WebSecurity.IsAuthenticated
Returns true if the current user is logged in.
[!code-csharpMain]
1: if(WebSecurity.IsAuthenticated) {...}
WebSecurity.IsConfirmed(userName)
Returns true if the user has been confirmed (for example, through a confirmation email).
[!code-csharpMain]
1: if(WebSecurity.IsConfirmed("joe@contoso.com")) { ... }
WebSecurity.IsCurrentUser(userName)
Returns true if the current user’s name matches the specified user name.
[!code-csharpMain]
1: if(WebSecurity.IsCurrentUser("joe@contoso.com")) { ... }
WebSecurity.Login(userName,password[, persistCookie])
Logs the user in by setting an authentication token in the cookie.
[!code-csharpMain]
1: if(WebSecurity.Login("username", "password")) { ... }
WebSecurity.Logout()
Logs the user out by removing the authentication token cookie.
[!code-cssMain]
1: WebSecurity.Logout();
WebSecurity.RequireAuthenticatedUser()
If the user is not authenticated, sets the HTTP status to 401 (Unauthorized).
[!code-cssMain]
1: WebSecurity.RequireAuthenticatedUser();
WebSecurity.RequireRoles(roles)
If the current user is not a member of one of the specified roles, sets the HTTP status to 401 (Unauthorized).
[!code-htmlMain]
1: WebSecurity.RequireRoles("Admin", "Power Users");
WebSecurity.RequireUser(userId)
WebSecurity.RequireUser(userName)
If the current user is not the user specified by username, sets the HTTP status to 401 (Unauthorized).
[!code-cssMain]
1: WebSecurity.RequireUser("joe@contoso.com");
WebSecurity.ResetPassword(passwordResetToken,newPassword)
If the password reset token is valid, changes the user’s password to the new password.
[!code-cssMain]
1: WebSecurity.ResetPassword( "A0F36BFD9313", "new-password")
Database.Execute(SQLstatement [,parameters]
Executes SQLstatement (with optional parameters) such as INSERT, DELETE, or UPDATE and returns a count of affected records.
[!code-sqlMain]
1: db.Execute("INSERT INTO Data (Name) VALUES ('Smith')");
2:
3: db.Execute("INSERT INTO Data (Name) VALUES (@0)", "Smith");
Database.GetLastInsertId()
Returns the identity column from the most recently inserted row.
[!code-sqlMain]
1: db.Execute("INSERT INTO Data (Name) VALUES ('Smith')");
2: var id = db.GetLastInsertId();
Database.Open(filename)
Database.Open(connectionStringName)
Opens either the specified database file or the database specified using a named connection string from the Web.config file.
[!code-csharpMain]
1: // Note that no filename extension is specified.
2: var db = Database.Open("SmallBakery"); // Opens SmallBakery.sdf in App_Data
3: // Opens a database by using a named connection string.
4: var db = Database.Open("SmallBakeryConnectionString");
Database.OpenConnectionString(connectionString)
Opens a database using the connection string. (This contrasts with Database.Open
, which uses a connection string name.)
[!code-csharpMain]
1: var db = Database.OpenConnectionString("Data Source=|DataDirectory|\SmallBakery.sdf");
Database.Query(SQLstatement[,parameters])
Queries the database using SQLstatement (optionally passing parameters) and returns the results as a collection.
[!code-htmlMain]
1: foreach (var result in db.Query("SELECT * FROM PRODUCT")) {<p>@result.Name</p>}
2:
3: foreach (var result = db.Query("SELECT * FROM PRODUCT WHERE Price > @0", 20))
4: { <p>@result.Name</p> }
Database.QuerySingle(SQLstatement [, parameters])
Executes SQLstatement (with optional parameters) and returns a single record.
[!code-csharpMain]
1: var product = db.QuerySingle("SELECT * FROM Product WHERE Id = 1");
2:
3: var product = db.QuerySingle("SELECT * FROM Product WHERE Id = @0", 1);
Database.QueryValue(SQLstatement [, parameters])
Executes SQLstatement (with optional parameters) and returns a single value.
[!code-csharpMain]
1: var count = db.QueryValue("SELECT COUNT(*) FROM Product");
2:
3: var count = db.QueryValue("SELECT COUNT(*) FROM Product WHERE Price > @0", 20);
Analytics.GetGoogleHtml(webPropertyId)
Renders the Google Analytics JavaScript code for the specified ID.
[!code-javascriptMain]
1: @Analytics.GetGoogleHtml("MyWebPropertyId")
Analytics.GetStatCounterHtml(project,security)
Renders the StatCounter Analytics JavaScript code for the specified project.
[!code-cssMain]
1: @Analytics.GetStatCounterHtml(89, "security")
Analytics.GetYahooHtml(account)
Renders the Yahoo Analytics JavaScript code for the specified account.
[!code-javascriptMain]
1: @Analytics.GetYahooHtml("myaccount")
Bing.SearchBox([boxWidth])
Passes a search to Bing. To specify the site to search and a title for the search box, you can set the Bing.SiteUrl
and Bing.SiteTitle
properties. Normally you set these properties in the _AppStart page.
[!code-htmlMain]
1: @Bing.SearchBox() @* Searches the web.*@
[!code-cshtmlMain]
1: @{
2: Bing.SiteUrl = "www.asp.net"; @* Limits search to the www.asp.net site. *@
3: }
4: @Bing.SearchBox()
Chart(width,height [, template] [, templatePath])
Initializes a chart.
[!code-cshtmlMain]
1: @{
2: var myChart = new Chart(width: 600, height: 400);
3: }
Chart.AddLegend([title] [, name])
Adds a legend to a chart.
[!code-cshtmlMain]
1: @{
2: var myChart = new Chart(width: 600, height: 400)
3: .AddLegend("Basic Chart")
4: .AddSeries(
5: name: "Employee",
6: xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" },
7: yValues: new[] { "2", "6", "4", "5", "3" })
8: .Write();
9: }
Chart.AddSeries([name] [, chartType] [, chartArea]
[, axisLabel] [, legend] [, markerStep] [, xValue]
[, xField] [, yValues] [, yFields] [, options])
Adds a series of values to the chart.
[!code-cshtmlMain]
1: @{
2: var myChart = new Chart(width: 600, height: 400)
3: .AddSeries(
4: name: "Employee",
5: xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" },
6: yValues: new[] { "2", "6", "4", "5", "3" })
7: .Write();
8: }
Crypto.Hash(string [, algorithm])
Crypto.Hash(bytes [, algorithm])
Returns a hash for the specified data. The default algorithm is sha256
.
[!code-htmlMain]
1: @Crypto.Hash("data")
Facebook.LikeButton(href [, buttonLayout] [, showFaces] [, width] [, height]
[, action] [, font] [, colorScheme] [, refLabel])
Lets Facebook users make a connection to pages.
[!code-javascriptMain]
1: @Facebook.LikeButton("www.asp.net")
FileUpload.GetHtml([initialNumberOfFiles] [, allowMoreFilesToBeAdded]
[, includeFormTag] [, addText] [, uploadText])
Renders UI for uploading files.
[!code-htmlMain]
1: @FileUpload.GetHtml(initialNumberOfFiles:1, allowMoreFilesToBeAdded:false,
2: includeFormTag:true, uploadText:"Upload")
GamerCard.GetHtml(gamerTag)
Renders the specified Xbox gamer tag.
[!code-javascriptMain]
1: @GamerCard.GetHtml("joe")
Gravatar.GetHtml(email [, imageSize] [, defaultImage] [, rating]
[, imageExtension] [, attributes])
Renders the Gravatar image for the specified email address.
[!code-cssMain]
1: @Gravatar.GetHtml("joe@contoso.com")
Json.Encode(object)
Converts a data object to a string in the JavaScript Object Notation (JSON) format.
[!code-csharpMain]
1: var myJsonString = Json.Encode(dataObject);
Json.Decode(string)
Converts a JSON-encoded input string to a data object that you can iterate over or insert into a database.
[!code-csharpMain]
1: var myJsonObj = Json.Decode(jsonString);
LinkShare.GetHtml(pageTitle[, pageLinkBack] [, twitterUserName]
[, additionalTweetText] [, linkSites])
Renders social networking links using the specified title and optional URL.
[!code-xmlMain]
1: @LinkShare.GetHtml("ASP.NET Web Pages Samples")
2: @LinkShare.GetHtml("ASP.NET Web Pages Samples", "http://www.asp.net")
ModelStateDictionary.AddError(key, errorMessage)
Associates an error message with a form field. Use the ModelState
helper to access this member.
[!code-csharpMain]
1: ModelState.AddError("email", "Enter an email address");
ModelStateDictionary.AddFormError(errorMessage)
Associates an error message with a form. Use the ModelState
helper to access this member.
[!code-powershellMain]
1: ModelState.AddFormError("Password and confirmation password do not match.");
ModelStateDictionary.IsValid
Returns true if there are no validation errors. Use the ModelState
helper to access this member.
[!code-csharpMain]
1: if (ModelState.IsValid) { // Save the form to the database }
ObjectInfo.Print(value [, depth] [, enumerationLength])
Renders the properties and values of an object and any child objects.
[!code-cssMain]
1: @ObjectInfo.Print(person)
Recaptcha.GetHtml([, publicKey] [, theme] [, language] [, tabIndex])
Renders the reCAPTCHA verification test.
[!code-cssMain]
1: @ReCaptcha.GetHtml()
ReCaptcha.PublicKey
ReCaptcha.PrivateKey
Sets public and private keys for the reCAPTCHA service. Normally you set these properties in the _AppStart page.
[!code-cssMain]
1: ReCaptcha.PublicKey = "your-public-recaptcha-key";
2: ReCaptcha.PrivateKey = "your-private-recaptcha-key";
ReCaptcha.Validate([, privateKey])
Returns the result of the reCAPTCHA test.
[!code-csharpMain]
1: if (ReCaptcha.Validate()) {
2: // Test passed.
3: }
ServerInfo.GetHtml()
Renders status information about ASP.NET Web Pages.
[!code-cshtmlMain]
1: @ServerInfo.GetHtml()
Twitter.Profile(twitterUserName)
Renders a Twitter stream for the specified user.
[!code-javascriptMain]
1: @Twitter.Profile("billgates")
Twitter.Search(searchQuery)
Renders a Twitter stream for the specified search text.
[!code-xmlMain]
1: @Twitter.Search("asp.net")
Video.Flash(filename [, width, height])
Renders a Flash video player for the specified file with optional width and height.
[!code-cshtmlMain]
1: @Video.Flash("test.swf", "100", "100")
Video.MediaPlayer(filename [, width, height])
Renders a Windows Media player for the specified file with optional width and height.
[!code-cshtmlMain]
1: @Video.MediaPlayer("test.wmv", "100", "100")
Video.Silverlight(filename, width, height)
Renders a Silverlight player for the specified .xap file with required width and height.
[!code-cshtmlMain]
1: @Video.Silverlight("test.xap", "100", "100")
WebCache.Get(key)
Returns the object specified by key, or null if the object is not found.
[!code-csharpMain]
1: var username = WebCache.Get("username")
WebCache.Remove(key)
Removes the object specified by key from the cache.
[!code-csharpMain]
1: WebCache.Remove("username")
WebCache.Set(key, value [, minutesToCache] [, slidingExpiration])
Puts value into the cache under the name specified by key.
[!code-htmlMain]
1: WebCache.Set("username", "joe@contoso.com ")
WebGrid(data)
Creates a new WebGrid
object using data from a query.
[!code-csharpMain]
1: var db = Database.Open("SmallBakery");
2: var grid = new WebGrid(db.Query("SELECT * FROM Product"));
WebGrid.GetHtml()
Renders markup to display data in an HTML table.
[!code-htmlMain]
1: @grid.GetHtml()// The 'grid' variable is set when WebGrid is created.
WebGrid.Pager()
Renders a pager for the WebGrid
object.
[!code-htmlMain]
1: @grid.Pager() // The 'grid' variable is set when WebGrid is created.
WebImage(path)
Loads an image from the specified path.
[!code-csharpMain]
1: var image = new WebImage("test.png");
WebImage.AddImagesWatermark(image)
Adds the specified image as a watermark.
[!code-csharpMain]
1: WebImage photo = new WebImage("test.png");
2: WebImage watermarkImage = new WebImage("logo.png");
3: photo.AddImageWatermark(watermarkImage);
WebImage.AddTextWatermark(text)
Adds the specified text to the image.
[!code-csharpMain]
1: image.AddTextWatermark("Copyright")
WebImage.FlipHorizontal()
WebImage.FlipVertical()
Flips the image horizontally or vertically.
[!code-cssMain]
1: image.FlipHorizontal();
2: image.FlipVertical();
WebImage.GetImageFromRequest()
Loads an image when an image is posted to a page during a file upload.
[!code-csharpMain]
1: var image = WebImage.GetImageFromRequest();
WebImage.Resize(width,height)
Resizes an the image.
[!code-cssMain]
1: image.Resize(100, 100);
WebImage.RotateLeft()
WebImage.RotateRight()
Rotates the image to the left or the right.
[!code-cssMain]
1: image.RotateLeft();
2: image.RotateRight();
WebImage.Save(path [, imageFormat])
Saves the image to the specified path.
[!code-javascriptMain]
1: image.Save("test.png");
WebMail.Password
Sets the password for the SMTP server. Normally you set this property in the _AppStart page.
[!code-csharpMain]
1: WebMail.Password = "password";
WebMail.Send(to, subject, body [, from] [, cc] [, filesToAttach] [, isBodyHtml]
[, additionalHeaders])
Sends an email message.
[!code-cssMain]
1: WebMail.Send("touser@contoso.com", "subject", "body of message",
2: "fromuser@contoso.com");
WebMail.SmtpServer
Sets the SMTP server name. Normally you set this property in the_AppStart page.
[!code-htmlMain]
1: WebMail.SmtpServer = "smtp.mailserver.com";
WebMail.UserName
Sets the user name for the SMTP server. Normally you should set this property in the _AppStart page.
[!code-htmlMain]
1: WebMail.UserName = "Joe";
Html.ValidationMessage(field)
(v2) Renders a validation error message for the specified field.
[!code-cshtmlMain]
1: <input type="text"
2: name="dateOfBirth"
3: value="" />
4: @Html.ValidationMessage("dateOfBirth")
Html.ValidationSummary([message])
(v2) Displays a list of all validation errors.
[!code-cshtmlMain]
1: @Html.ValidationSummary()
2:
3: @Html.ValidationSummary("The following validation errors occurred:")
Validation.Add(field, validationType)
(v2) Registers a user input element for the specified type of validation.
[!code-javascriptMain]
1: Validation.Add("dateOfBirth", Validator.DateTime("Date of birth was not valid"));
2: Validation.Add("quantity", Validator.Integer("Enter a number"));
3: Validation.Add("confirmPassword",
4: Validator.EqualsTo("password", "Passwords must match."));
Validation.ClassFor(field)
(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.)
[!code-htmlMain]
1: <head>
2: <script
3: src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js">
4: </script>
5: <script
6: src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.js">
7: </script>
8: <script
9: src="~/Scripts/jquery.validate.unobtrusive.js">
10: </script>
11:
12: <style>
13: input-validation-error{ /* style rules */ }
14: field-validation-error{ /* style rules */ }
15: validation-summary-errors{ /* style rules */ }
16: field-validation-valid{ /* style rules */ }
17: input-validation-valid{ /* style rules */ }
18: validation-summary-valid{ /* style rules */ }
19: </style>
20: </head>
21:
22: ...
23:
24: <input
25: type="text"
26: name="firstName"
27: @Validation.For("firstName") @Validation.ClassFor("firstName") />
Validation.For(field)
(v2) Enables client-side validation for the user input field. (Requires that you reference the appropriate client-script libraries.)
[!code-htmlMain]
1: <head>
2: <script
3: src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js">
4: </script>
5: <script
6: src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.js">
7: </script>
8: <script
9: src="~/Scripts/jquery.validate.unobtrusive.js">
10: </script>
11: </head>
12:
13: ...
14:
15: <input
16: type="text"
17: name="firstName"
18: @Validation.For("firstName") />
Validation.IsValid()
(v2) Returns true if all user input elements that are registred for validation contain valid values.
[!code-csharpMain]
1: if(IsPost){
2: if (Validation.IsValid()) {
3: // Process input
4: }
5: }
Validation.RequireField(field[, errorMessage])
(v2) Specifies that users must provide a value for the user input element.
[!code-csharpMain]
1: Validation.RequireField("dateOfBirth", "Date of birth is required");
Validation.RequireFields(field1[, field12, field3, ...])
(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.
[!code-htmlMain]
1: Validation.RequireFields("firstName", "lastName", "dateOfBirth");
Validator.DateTime ([error message])
Validator.Decimal([error message])
Validator.EqualsTo(otherField,[error message])
Validator.Float([error message])
Validator.Integer([error message])
Validator.Range(min,max [, error message])
Validator.RegEx(pattern[, error message])
Validator.Required([error message])
Validator.StringLength(length)
Validator.Url([error message])
(v2) Specifies a validation test when you use the Validation.Add
method.
[!code-javascriptMain]
1: Validation.Add("dateOfBirth", Validator.DateTime("Date of birth was not valid"));
2: Validation.Add("quantity", Validator.Integer("Enter a number"));
3: Validation.Add("confirmPassword", Validator.EqualsTo("password",
4: "Passwords must match."));
|