You are on page 1of 36

Application Folders Html Helpers

used to render (modify and output) HTML form


App_Start elements
It has configuration classes to reduce clutter code in
the Global.asax Application_Start method. It Html.ActionLink
contains following files:
Output: <a href=".."...>..</a>
- AuthConfig.cs
Html.BeginForm
Related to security settings, including sites for OAuth
login. Output: <form ...>

- BundleConfig.cs Html.CheckBox

Related to register bundles for the bundling and Output: <input type="checkbox" .../>
minification Html.DropDownList
- FilterConfig.cs Output: <select ..> .. </select>
To register global MVC filters.(by default Html.EndForm
HandleErrorAttribute is registered)
Output: </form>
- RouteConfig.cs
Html.Hidden
Related to MVC Route configuration
Output: <input type="hidden" ... />
- WebApiConfig.cs
Html.ListBox
Used to register Web API routes and configuration
settings Output: <select multiple ...>...</select>

Areas Html.Password
An MVC structure inside the application to partition Output: <input type="password" ... />
our web application into smaller parts. Html.RadioButton
Content Output: <input type="radio" .. />
To put CSS and other static contents Html.TextArea
Controllers Output: <textarea...>...</textarea>
Contains the controller classes Html.TextBox
Images Output: <input type="text" ... />
For images, It is being referenced from the Content\ Html.ValidationSummary
Site.css by default.
Returns an unordered list (ul element) of validation
Models messages that are in the ModelStateDictionary
Contains view model and domain model classes. object.

Scripts Html.ValidationMessage
Stores all JavaScript libraries and files To display an error for a particular field in the
ModelState dictionary
Views
Html.RouteLink
Related to the display of the application (UI).
To generate a URL to a specific route
View Related & Others Action Method Result
@{ Layout = "..."} ActionResult
To define layout page Equivalent to asp.net master- generic return value for an action and is used to
page perform a framework-level operation.
@model <StrongModelType> ContentResult
To define strongly-typed model To return a user-defined content type that is the
result of an action method.
@section <name> { }
EmptyResult
To define named section
To return nothing from a Controller action
@RenderBody
FileContentResult
Used in layout as a placeholder for view's entire
content. Sends the contents of a binary file to the response.
@RenderPage FilePathResult
Renders the content of one page within another Sends the contents of a file to the response.
page.
FileResult
@RenderSection
To return the content of a file to the browser
In layout pages, renders the content of a named
section.
FileStreamResult
Sends binary content to the response by using a
IsSectionDefined
Stream instance.
Returns a value that indicates whether the specified
section is defined in the page.
HttpNotFoundResult
To return 404 status-code to indicate that the
DefineSection
requested resource was not found.
To create named content sections in content page.
HttpStatusCodeResult
@helper
To return HTTP response status code and desc.
To define a helper which create a reusable code
snippet.
HttpUnauthorizedResult
To return 401 status code to indicate unauthorized
@functions
HTTP request.
To define a function ( pure server-side methods)that
can be reused within the view.
JsonResult
To return a serialized JSON object.
@ViewBag.<myData>
Dynamic property, used to pass data between a
JavaScriptResult
Controller and a View To return a script that can be executed on the client.
@ViewData[myData] PartialViewResult
To pass data between a Controller and a View via To render a partial view (fx. just a user control)
special Dictionary class
RedirectResult
@tempdata
To redirect to a specified URI.
To pass State Between Action Methods
RedirectToRouteResult
to redirect to a route
ValueProviderResult
Represents the result of binding a value (such as
from a form post or query string) to an action-method
argument property, or to the argument itself.
ViewEngineResult
Represents the result of locating a view engine.
ViewResult To Render a view as a Web page.
Attributes Data Annotations for Model
[AcceptVerbs(...)] To specify HTTP verbs an [Bind(...)]
action method will respond to.
Lists fields to exclude or include when binding
[ActionName(...)] To define the name of an action parameter or form values to model properties
[AdditionalMetadata(...)]
[Compare("...")]
to populate the ModelMetadata.AdditionalValues
dictionary for a model property. To compare two properties.

[AllowHtml] To allow HTML markup during model [CreditCard]


binding by skipping request validation for the To Specify that a data field value is a credit card
property. number.
[AsyncTimeout(...)] [DataType(DataType.<type>)]
To set the timeout value, in milliseconds, for an
used for formatting purposes, not for validation.
asynchronous method.
[DisplayName (...)]
[Authorize(...)] To restrict access by callers to an
action method. Defines the text we want used on form fields and
[ChildActionOnly] To indicate that an action validation messages
method should be called only as a child action. [EmailAddress]
[HandleError(...)]
To validate an email address
to handle an exception that is thrown by an action
method. [FileExtensions(Extensions = "jpg,png...")]
To Validate file name extensions.
[HiddenInput(...)] To render a property or field
value as a hidden input element. [key]
[HttpDelete] to restrict an action method to handle To denote one or more properties that uniquely
only HTTP DELETE requests. identify an entity.
[HttpGet] to restrict an action method to handle
only HTTP Get requests. [MaxLength(...)]
[HttpPost] to restrict an action method to handle To define the maximum length of array or string data
only HTTP Post requests. allowed in a property.
[HttpPut] to restrict an action method to handle [MinLength(...)]
only HTTP Put requests.
[ModelBinder(..)] To define the minimum length of array of string data
allowed in a property.
to associate a model type to a model-builder type.
[Phone..]
[NoAsyncTimeout] To set the timeout to infinite
(never). To Specify for phone number using a regular
expression.
[NonAction] To indicate that a controller method is
not an action method. [Range (...)]
[OutputCache(..)] Gives a maximum and minimum value for a numeric
To mark an action method whose output will be field
cached. [RegularExpression(...)]
[Remote(...)] To specify that a data field value must match the
It is used to invoke the server-based validation from specified regular expression.
client side. [Required (...)]
[RequireHttps] It forces an unsecured HTTP Indicates that the property is a required field
request to be re-sent over HTTPS.
[SessionState(...)] [StringLength(...)]

Specifies the session state of the controller. Defines a maximum length for a string field

[ValidateInput(...)] [ScaffoldColumn(...)]

To mark action methods whose input must be Allows hiding fields from editor forms
validated. [Url] It provides URL validation.
Attributes Html Helpers
ActionFilterAttribute @Html.AntiForgeryToken
Represents the base class for filter attributes. It generates a hidden form field (anti-forgery token)
that is validated when the form is submitted.
ActionMethodSelectorAttribute
@Html.AttributeEncode
Represents an attribute that is used to influence the
selection of an action method. To convert the specified attribute value to an HTML-
encoded string.
ActionNameSelectorAttribute
@Html.Encode
Represents an attribute that affects the selection of
an action method. To convert the specified value to an HTML-encoded
string.
CustomModelBinderAttribute
@{ Html.EnableClientValidation(); }
It invokes a custom model binder.
To enables or disables client validation
FilterAttribute
Html. EnableUnobtrusiveJavaScript
base class for action and result filter attributes.
To enables or disables unobtrusive JavaScript.
@Html.FormatValue
To format value
@Html.Raw
To return markup that is not HTML encoded.
@Html.Partial
To render a partial view into a string.
@{Html.RenderPartial(..);}
writes directly to the response output stream instead
of returning a string.
@Html.Action
executes a separate controller action and returns as
string
Html.RenderAction
executes a separate controller action and render the
result directly to the Response
ASP.NET Cheatsheet

MVC
Model–view–controller (MVC) is an architectural pattern commonly used for developing user
interfaces that divides an application into three interconnected parts. This is done to separate internal
representations of information from the ways information is presented to and accepted from the user.

Controller accepts input and converts it to commands for the model or view. It is a class which
contains actions and functions. A request to controller can be made by

http://web-address/controller-name/function-name
Model is responsible for managing the data of the application.

View means presentation of the model in a particular format. It can be output representation of


information, such as a chart or a diagram. Multiple views of the same information are possible, such
as a bar chart for management and a tabular view for accountants.

Controller
Controller accepts input and converts it to commands for the model or view. It is a class which
contains actions and functions.

Basic Controller
(As per ASP.NET MVC's conventions) Create a BasicController.cs in Controllers directory and add
following code

using System.Web.Mvc;

namespace myWeb.Controllers
{
public class BasicController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
To call this action, go to

http://web-address/basic/index/
It will return the HTML code in index.cshtml file placed in Views folder.

Note: We use basic instead of BasicController in URL for controller name.

Action Verb
Action Verbs are used to control the selection of action based on request method. There are different
action verbs available in ASP.NET MVC. For example HttpPost, HttpGet and HttpDelete
[HttpGet]
//Accepts only Get requests
public ActionResult GetMethod(int id) { ... }

//Accepts both Post and Get requests


[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]
public ActionResult PostAndGetMethod(MyEditViewModel myEditViewModel) { ... }

Basic View
(As per ASP.NET's conventions) Create hello.cshtml in Views folder and add following code

<h1>Hello ASP.NET</h1>
Now, you can add function for this view in your controller.

Razor
Razor is a markup syntax for embedding server-based code into webpages. The Razor syntax consists
of Razor markup, C#, and HTML. Files containing Razor generally have a .cshtml file extension.

For more details, visit A Razor Cheatsheet.

Layout
Most web apps have a common layout that provides the user with a consistent experience as they
navigate from page to page. The layout typically includes common user interface elements such as
the app header, navigation or menu elements, and footer.

By convention, the default layout for an ASP.NET app is named _Layout.cshtml. This layout defines a
top level template for views in the app. Apps don't require a layout, and apps can define more than
one layout, with different views specifying different layouts.

Specify Layout for a View


Razor views have a Layout property. Individual views specify a layout by setting this property:
@{
Layout = "_Layout";
}
The layout specified can use a full path (example: /Views/Shared/_Layout.cshtml) or a partial name
(example: _Layout). When a partial name is provided, the Razor view engine will search for the layout
file using its standard discovery process. The controller-associated folder is searched first, followed by
the Shared folder. This discovery process is identical to the one used to discover partial views.
By default, every layout must call RenderBody. Wherever the call to RenderBody is placed, the contents of
the view will be rendered.
Note: Default layout is defined in Views/_ViewStart.cshtml file.

Section in a Layout
Sections provide a way to organize where certain page elements should be placed. A layout can
optionally reference one or more sections, by calling RenderSection. Each call to RenderSection can
specify whether that section is required or optional. If a required section isn't found, an exception will
be thrown. Individual views specify the content to be rendered within a section using
the @section Razor syntax. If a view defines a section, it must be rendered (or an error will occur).
An example @section in a view:
@section Scripts
{
<script type="text/javascript" src="/scripts/main.js"></script>
}

Basic Layout
(As per ASP.NET conventions) Create a _MyLayout.cshtml file in ~/Views/Shared/ folder and add
following code
@
{
Layout = null;
}
<html>
<head>
<title>My Web</title>
</head>
<body>
@RenderBody()

<div id="footer">
@RenderSection("footer", false);
</div>
</body>
</html>
Code of view that uses this layout:

@
{
Layout = "~/Views/Shared/_MyLayout.cshtml";
}

<p> Body of view </p>

@section footer
{
<p>Footer area</p>
}
HTML that will be rendered for this view is:

<html>
<head>
<title>My Web</title>
</head>
<body>
<p> Body of view </p>

<div id="footer">
<p>Footer area</p>
</div>
</body>
</html>

Send Data from Controller to View


There three ways to send data from Controller to View.
ViewBag
ViewBag can be useful when you want to transfer temporary data (which is not included in model)
from the controller to the view. The ViewBag is a dynamic type property. You can assign any number
of properties and values to ViewBag. If you assign the same property name multiple times to
ViewBag, then it will only consider last value assigned to the property.

Note: The ViewBag's life only lasts during the current http request. ViewBag values will be null if
redirection occurs.

We use dot notationg to send data from controller.

public ActionResult Index()


{
ViewBag.PageTitle = "This is the page title";
ViewBag.PageDescription = "This is the page description. We'll make it rather longer.";

return View();
}
This can be accessed in the view like @ViewBag.PageTitle.

<h3>@ViewBag.PageTitle</h3>

<p>
@ViewBag.PageDescription
</p>
Note: ViewBag is a wrapper around ViewData. It will throw a runtime exception, if the ViewBag
property name matches with the key of ViewData.

ViewData
ViewData is similar to ViewBag. It is useful in transferring data from Controller to View. It is a
dictionary which can contain key-value pairs where each key must be string.

Note: The ViewData's life only lasts during the current http request. ViewData values will be null if
redirection occurs.

ViewData is liked a dictionary and we use same syntax as of dictionary to send data from controller.

public ActionResult Index()


{
ViewData["PageTitle"] = "This is the page title";
ViewData["PageDescription"] = "This is the page description. We'll make it rather longer.";

return View();
}
This can be accessed in the view like @ViewBag.PageTitle.

<h3>@ViewData["PageTitle"]</h3>

<p>
@ViewData["PageDescription"]
</p>
Note: ViewData is a wrapper around ViewBag. It will throw a runtime exception, if the ViewBag
property name matches with the key of ViewData.
ViewModel
We can pass the Model class to View to send data.

public ActionResult Index()


{
Product prod = new Product
{
Id = 1,
Name = "Golf cap",
Description = "A nice cap to play golf",
price = 10m
};

return View(prod);
}
To use this in view, we need to tell the view the type of model it is receiving.

@using AppName.Models
@model AppName.Models.Product

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<h1>Product</h1>
<h3>ID: @Model.Id</h3>
<h3>Name: @Model.Name </h3>
<h3>Description: @Model.Description</h3>
<h3>Price: @Model.price</h3>
Note: We can only send one object using this method. To send more than one object, we need to
compose them into a single class then send that class using this method.
Razor Cheatsheet

Introduction
Razor is a markup syntax for embedding server-based code into webpages. The Razor syntax consists
of Razor markup, C#, and HTML. Files containing Razor generally have a .cshtml file extension.

Razor Code Block


A razor block consists of

@{
//Your code here
}
You can use any C# code in razor block.

Render HTML
Anything in Razor Block that is not C#, will be rendered as HTML. For exmaple

@{
for(int i = 0; i < 3; i++)
<span>Hello</span>
}
Will be rendered in HTML as

<span>Hello</span>
<span>Hello</span>
<span>Hello</span>

Use Variables in HTML


We can use C# variables in our HTML code by prefixing its name with @
@{
var myGreetings = "Hello World";
}

<p>myGreetings: @myGreetings</p>
It will be rendered as myGreetings: Hello World
Note To escape @ in Razor Markup, use a second @ with symbol
<p>@@myvar</p>
It will be rendered as

<p>@myVar</p>

Section
We can define a section that can be used in a layout as follows:

@section section_name
{
<h1>Hello Section</h1>
}
Syntax /
Razor Example Remarks
Sample

Simply prefix with the @ character to access a


Implicit @name variable, a class or a function. Be aware that
expression > Show extended example the output will be automatically HTML
encoded.

The explicit impression should be used when


you want to do something that might
Explicit @(5+5) otherwise confuse the parser. For instance, if
expression > Show extended example you need to access a variable in the middle of
a string or if you want to do
calculations/modifications to the output.

Unencoded @Html.Raw(name) The same as the implicit expression, but the


expression > Show extended example output will not be HTML encoded.

Multi- @{ A Razor code block starts with a combination


statement /* C# Code goes here */ of the @-character and the {-character and
code } ends with the } character. Inside of this, you're
blocks > Show extended example now writing C# code.

When you're inside a code block, either


because of a control structure (like in the
Plain text @:Plain text goes here... example) or because you have explicitly
inside a > Show extended example defined one, you can output plain text by
code block
prefixing with a @-character followed by a :
(colon) character.

When you're inside a code block, either


Plain text
<text>Plain text goes because of a control structure (like in the
inside a here...</text> example) or because you have explicitly
code block > Show extended example defined one, you can output plain text by
(alternative)
surrounding it with <text> tags.

@*
Here's a Razor If you need to, you can easily write Razor
server-side comment comments in your code. They are a great
Server-side It won't be rendered alternative to HTML comments, because
comment to the browser the Razor comments won't be included in
It can span multiple
lines*@ the output to the browser.

With this syntax, you don't have to check for


NULL values you want an HTML attribute to
Conditional <div
use a variable value. In the example,
attribute (N style="@divStyle">Hello,
world!</div> the style attribute will only be rendered if the
ew in MVC
> Show extended example variable divStyle has a non-NULL
4)
value. Please be aware that the variable
still has to be declared!
ASP.NET Core Basic Security Settings Cheatsheet
When starting a new project, looking at a new framework, or fixing vulnerabilities identified as part
of an assessment or tool, its nice to have one place to refer to the fixes for common security issues. This
post provides solutions for some of the more basic issues, especially those around configuration. Most of
these answers can be found in Microsoft's documentation or by doing a quick Google search. But
hopefully having it all right here will save others some time.

Enabling An Account Lockout Response


To enable the account lockout response for ASP.NET Identity, first modify the Startup.cs file to
choose appropriate settings. In the ConfigureServices method, add the following code:
services.Configure<IdentityOptions>(options =>
{
  //optional
  options.Lockout.AllowedForNewUsers = true;
  //requires manual unlock
  options.Lockout.DefaultLockoutTimeSpan = TimeSpan.MaxValue;
  //three failed attempts before lockout
  options.Lockout.MaxFailedAccessAttempts = 3; 
});
With the settings configured, lockout still needs to be enabled in the login method of the account
controller. In AccountController -> Login(LoginViewModel model, string returnUrl = null), change
lockoutOnFailure from false to true as shown below:
var result = await _signInManager.PasswordSignInAsync(model.Email,
model.Password, model.RememberMe, lockoutOnFailure: true);

Defining and Enforcing an Application Specific Password Policy


ASP.NET Identity comes with a class that validates passwords. It is configurable and allows one to
decide if passwords should require a digit, uppercase letters, lowercase letters, numbers, and/or a
symbol. This policy can be further customized by implementing the IPasswordValidator interface or
extending the Microsoft.AspNetCore.Identity.PasswordValidator. The code below extends the
PasswordValidator and ensures the password does not contain an individual's username.
using ASPNETCoreKestrelResearch.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System.Threading.Tasks;

namespace ASPNETCoreKestrelResearch.Security
{public class CustomPasswordValidator<TUser> : PasswordValidator<TUser> where
TUser : IdentityUser
    {
   public override async Task<IdentityResult>
ValidateAsync(UserManager<TUser> manager, TUser user, string password)
        {            
          IdentityResult baseResult = await base.ValidateAsync(manager,
user, password);

     if (!baseResult.Succeeded)
                return baseResult;
     else
     {
     if (password.ToLower().Contains(user.UserName.ToLower()))
       {                    
         return IdentityResult.Failed(new IdentityError
           {
             Code = "UsernameInPassword",
             Description = "Your password cannot contain your username"
           });
           }
           else
             return IdentityResult.Success;
            }        }    } }

Next, ASP.NET Identity needs to be told to use that class. In the ConfigureServices method of
Startup.cs, find services.AddIdentity and add
".AddPasswordValidator<CustomPasswordValidator<ApplicationUser>>();" as shown below.
services.AddIdentity<ApplicationUser, IdentityRole>()
  .AddEntityFrameworkStores<ApplicationDbContext>()
  .AddDefaultTokenProviders()
  .AddPasswordValidator<CustomPasswordValidator<ApplicationUser>>();

Choosing a Session Timeout Value


Developers can choose how long a session cookie remains valid and whether a sliding expiration
should be used by adding the following code to the ConfigureServices method of Startup.cs:
services.Configure<IdentityOptions>(options =>
{
  options.Cookies.ApplicationCookie.ExpireTimeSpan =
TimeSpan.FromMinutes(10);
  options.Cookies.ApplicationCookie.SlidingExpiration = true;
});
Enabling the HTTPOnly and Secure Flag for Authentication Cookies
First, if you are using Kestrel, HTTPS (TLS) is not supported. Instead, it is implemented by
HAProxy, Nginix, Apache, IIS, or some other web server you place in front of the application. If you are
using Kestrel, the Secure flag cannot be enabled properly from the application code. However, if you are
hosting the application in IIS directly, then it will work. The following code demonstrates enabling both the
HTTPOnly and Secure flags for cookie middleware in ASP.NET Identity through the ConfigureServices
method in Startup.cs.
services.Configure<IdentityOptions>(options =>
{
  options.Cookies.ApplicationCookie.CookieHttpOnly = true;
  options.Cookies.ApplicationCookie.CookieSecure =
CookieSecurePolicy.Always;
});
Enabling Cache-Control: no-store
When applications contain sensitive information that should not be stored on a user's local hard
drive, The Cache-Control: no-store HTTP response header can help provide that guidance to browsers.
To enable that feature, add the following code to the ConfigureServices method in Startup.cs.
services.Configure<MvcOptions>(options =>
{
  options.CacheProfiles.Add("DefaultNoCacheProfile", new CacheProfile
  {
    NoStore = true,
    Location = ResponseCacheLocation.None
  });
  options.Filters.Add(new ResponseCacheAttribute
  {
    CacheProfileName = "DefaultNoCacheProfile"                    
  });
});
Disabling the Browser's Autocomplete Feature for Login Forms
The changes to ASP.NET's razor views makes this super simple. Just add the autocomplere="off"
attribute as if it were a normal HTML input field:
<input asp-for="Email" class="form-control" autocomplete="off"/>
<input asp-for="Password" class="form-control" autocomplete="off"/>

Modify The Iterations Count for the Password Hasher's Key Derivation Function
First, I believe the default right now is 10,000 and the algorithm is PBKDF2. The code below won't
change that default iteration count, but it will show how it can be done. In ConfigureService in Startup.cs
add the following code.
services.Configure<PasswordHasherOptions>(options =>
{                
  options.IterationCount = 10000;
});
Enforcing HTTPS and Choosing Appropriate TLS Protocols and Cipher Suites
As mentioned above, if you are using Kestrel you won't be able to use HTTPS directly. Therefore,
you won't do this in your code. You will need to look up how to do this in HAProxy, Nginx, Apache, IIS,
etc. If you are hosting your application using IIS directly, then you can enforce the use of HTTPS using
something like https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/
RequireHttpsAttribute.cs BUT, it will only be applied to your MVC controllers/views. It will not be enforced
for static content (see https://github.com/aspnet/Home/issues/895). If you want to do this in code, you will
need to write some middleware to enforce it across the entire application. Finally, the choice of cipher
suites offered cannot be changed using code.
Enabling a Global Error Handler
A custom global error handler is demonstrated by the Visual Studio template. The following
relevant code can be found in the Configure method of Startup.cs.
if (env.IsDevelopment())
{
  app.UseDeveloperExceptionPage();
  app.UseDatabaseErrorPage();
  app.UseBrowserLink();
}
else
{
  app.UseExceptionHandler("/Home/Error");
}
Removing the Server HTTP Response Header
All responses from the server are going to return "Server: Kestrel" by default. To remove that
value, modify UseKestrel() in Program.cs to include the following settings change:
public static void Main(string[] args)
{
  var host = new WebHostBuilder()
    .UseKestrel(options =>
  {
      options.AddServerHeader = false;
    })
  .UseContentRoot(Directory.GetCurrentDirectory())
  .UseIISIntegration()
  .UseStartup<Startup>()
  .UseUrls("http://0.0.0.0:5000")
  .Build();
  host.Run();
}
X-Frame-Options, Content-Security-Policy, and Strict-Transport-Security
HTTP Response Headers
The following post seems to cover most of these headers well: http://andrewlock.net/adding-
default-security-headers-in-asp-net-core/. I haven't evaluated its design, but I did verify that I can install it
and the headers are added successfully. Since Kestrel does not support HTTPS, consider whether its
appropriate to implement the Strict-Transport-Security header using code or by configuring the web
server placed in front of the application.

I installed this nuget package using "Install-Package


NetEscapades.AspNetCore.SecurityHeaders". Then, I made sure to have the following imports in
Startup.cs:
using NetEscapades.AspNetCore.SecurityHeaders;
using NetEscapades.AspNetCore.SecurityHeaders.Infrastructure;
I added the following code to the ConfigureService method of Startup.cs:
services.AddCustomHeaders();
Last, I added this code to the Configure method of Startup.cs:
app.UseCustomHeadersMiddleware(new HeaderPolicyCollection()
  .AddContentTypeOptionsNoSniff()
  .AddFrameOptionsDeny()
  //.AddStrictTransportSecurityMaxAge()
  .AddXssProtectionBlock()
  //.AddCustomHeader("Content-Security-Policy", "somevaluehere")
  //.AddCustomHeader("X-Content-Security-Policy", "somevaluehere")
  //.AddCustomHeader("X-Webkit-CSP", "somevaluehere")
);
Make sure you add this code BEFORE app.UseStaticFiles();, otherwise the headers will not be
applied to your static files.
The ASP.NET Core Form Tag Helpers Cheat Sheet
The Form itself (MVC)
CSHTML
@model FormsCheatSheet.Models.Example

<form asp-controller="Example" asp-action="Save" >


<button type="submit">Submit Form</button>
</form>

The Controller
public class ExampleController : Controller
{
public IActionResult Index()
{
return View(new Example());
}

[ValidateAntiForgeryToken]
public IActionResult Save(Example model)
{
// do something with model e.g. model.Name
return Ok();
}
}

Resulting HTML
<form action="/Example/Save" method="post">
<input name="__RequestVerificationToken" type="hidden"
value="<random-looking-value=here>">
</form>

Using default ASP.NET Core MVC routing, a request to view  https://<your-app-here>/example  will invoke
the  Index  method which returns  Example\Index.cshtml  (including our form).
When that form is submitted, the data will be routed to  Save  and the model populated with any submitted
values.
The  __RequestVerificationToken  is automatically generated by ASP.NET and included as a hidden field.
When the form is submitted this will be included in the form data and ASP.NET will validate it to ensure this is
a legitimate request.
This helps ensure the form isn’t some spoof form someone has created on a different web site, pointing to your
application.
The Form itself (Razor Pages)
CSHTML
@model FormsCheatSheet.Models.Example

<form asp-page="About">
<button type="submit">Submit Form</button>
</form>

The Razor Page (About.cshtml.cs)


public class AboutModel : PageModel
{
public void OnGet()
{
}

public void OnPost()


{
// form will submit to here
}
}

Resulting HTML
<form action="/About" method="post">
<input name="__RequestVerificationToken" type="hidden"
value="<random-looking-value=here>">
</form>

Here we explicitly inform ASP.NET that this form will post back to the About page.
ASP.NET Core will then attempt to locate and invoke an  OnPost  method in the About Page’s Page Model
( About.cshtml.cs ) to handle the submitted form data.

Label
CSHTML
<label asp-for="Name"></label>

Model
[Display(Name = "Full Name")]
public string Name { get; set; }

Resulting HTML
<label for="Name">Full Name</label>

If you provide a  [Display(Name=""])  its value will be used for the label, otherwise you’ll just get the name of
the property itself e.g.  Name .
Text Input
CSHTML
<input asp-for="Name" />

Model
public string Name { get; set; }

Resulting HTML
<input type="text" id="Name" name="Name" value="">

ASP.NET Core will infer that this should be an input of type  text  because the ‘Name’ property on the model is
a string.
When this form is submitted the  Name  property on the model will be populated using the value entered in the
form.

Password Input
CSHTML
<input asp-for="Password" />

Model
[DataType(DataType.Password)]
public string Password { get; set; }

Resulting HTML
<input type="password" id="Password" name="Password">

ASP.NET Core will infer that this should be an input of type  password  because of the  [DataType]  attribute.
Alternatively you can just specify this yourself in the CSHTML markup e.g.  <input asp-for="Password"
type="password"/> .

When this form is submitted,  Password  will be populated using the value entered in the form.

Textarea
CSHTML
<textarea asp-for="Bio" />

Model
public string Bio { get; set; }

Resulting HTML
<textarea id="Bio" name="Bio"></textarea>

When submitted,  Bio  will be populated using the value entered.

Dropdown list (Select)


CSHTML
<select asp-for="Country" asp-items="Model.Countries"></select>
Model
public List<SelectListItem> Countries { get; set; }
= new List<SelectListItem>
{
new SelectListItem("UK", "UK"),
new SelectListItem("USA", "USA"),
new SelectListItem("France", "FR")
}; // used to populate the list of options

public string Country { get; set; }

Resulting HTML
<select id="Country" name="Country">
<option value="UK">UK</option>
<option value="USA">USA</option>
<option value="FR">France</option>
</select>

The  select  tag helper needs to know where to fetch its list of options from.
Unlike the  asp-for  attribute (which assumes everything you try to use is on the Model), you have to explicitly
tell  asp-items  where the list is coming from. In this case,  Model.Countries .
When the form is submitted  Country  will be set to the selected value in the dropdown list.

Hidden Field
CSHTML
<input asp-for="ApplicationType" />

Model
[HiddenInput]
public string ApplicationType { get; set; } = "Online";

Resulting HTML
<input type="hidden" id="ApplicationType" name="ApplicationType" value="Online">

Occasionally you may need to include a value in the submitted form data but not show it on the page.
You can use hidden fields for this, setting them to a value which will then be posted back when the form is
submitted.
The  [HiddenInput]  attribute means that ASP.NET will infer this should be a hidden field.
Alternatively you can set this yourself in the CSHTML.
<input type="hidden" asp-for="ApplicationType">

In this example the  ApplicationType  of ‘Online’ will be sent “up” to the client and rendered as a hidden input.
When the form is subsequently submitted this value will be included in the submitted form data and
the  ApplicationType  property on the model will be set accordingly.
Checkbox
CSHTML
<input asp-for="AcceptsTerms" />

Model
public bool AcceptsTerms { get; set; }

Resulting HTML
<input type="checkbox" data-val="true" id="AcceptsTerms"
data-val-required="The AcceptsTerms field is required."
name="AcceptsTerms" value="true">

ASP.NET Core will infer that the input should be of type “checkbox” if you point it at a Boolean property on
your model.
The  value  attribute here is a little confusing as it seems to always be  true . However, there is another attribute
which isn’t visible in the rendered markup called  checked  and this is the important one which will change
depending on whether the checkbox is ticked or not.
When the form is submitted the posted form data will include a  true  or  false  and the  AcceptTerms  property on
the model will be populated accordingly.
Because the boolean property on the model cannot be null (has to be either true or false) ASP.NET also
generates validation attributes here indicating that this input is required.
This is largely irrelevant though as, even f your users don’t touch the checkbox, a  false  value will be posted
when the form is submitted and the Model property will be set accordingly.

Radio Button
CSHTML
<label><input asp-for="Gender" value="M" type="radio" />Male</label>
<label><input asp-for="Gender" value="F" type="radio"/>Female</label>

Model
public string Gender { get; set; }

Resulting HTML
<label><input value="M" type="radio" id="Gender" name="Gender">Male</label>
<label><input value="F" type="radio" id="Gender" name="Gender">Female</label>

Radio Buttons are different to checkboxes in that they generally come in groups of two or more and you can
only select on of the possible options.
In this scenario the user can select Male or Female and the  Gender  property on the model will be set
accordingly.
REGEX CHEAT SHEET
Metacharacters Defined
MChar Definition
^ Start of a string.
$ End of a string.
. Any character (except \n newline)
| Alternation.
{...} Explicit quantifier notation.
[...] Explicit set of characters to match.
(...) Logical grouping of part of an expression.
* 0 or more of previous expression.
+ 1 or more of previous expression.
? 0 or 1 of previous expression; also forces minimal matching when an expression might match several
strings within a search string.
\ Preceding one of the above, it makes it a literal instead of a special character. Preceding a special
matching character, see below.

Metacharacter Examples
Pattern Sample Matches
^abc abc, abcdefg, abc123, ...
abc$ abc, endsinabc, 123abc, ...
a.c abc, aac, acc, adc, aec, ...
bill|ted ted, bill
ab{2}c abbc
a[bB]c abc, aBc
(abc){2} abcabc
ab*c ac, abc, abbc, abbbc, ...
ab+c abc, abbc, abbbc, ...
ab?c ac, abc
a\sc ac
Character Escapes 
Escaped Char Description
ordinary Characters other than . $ ^ { [ ( | ) ] } * + ? \ match themselves.
characters
\a Matches a bell (alarm) \u0007.
\b Matches a backspace \u0008 if in a []; otherwise matches a word boundary
(between \w and \W characters).
\t Matches a tab \u0009.
\r Matches a carriage return \u000D.
\v Matches a vertical tab \u000B.
\f Matches a form feed \u000C.
\n Matches a new line \u000A.
\e Matches an escape \u001B.
\040 Matches an ASCII character as octal (up to three digits); numbers with no leading
zero are backreferences if they have only one digit or if they correspond to a
capturing group number. (For more information, see Backreferences.) For
example, the character \040 represents a space.
\x20 Matches an ASCII character using hexadecimal representation (exactly two digits).
\cC Matches an ASCII control character; for example \cC is control-C.
\u0020 Matches a Unicode character using a hexadecimal representation (exactly four
digits).
\* When followed by a character that is not recognized as an escaped character,
matches that character. For example, \* is the same as \x2A.
Character Classes
Char Class Description
. Matches any character except \n. If modified by the Singleline option, a period
character matches any character. For more information, see Regular Expression
Options.
[aeiou] Matches any single character included in the specified set of characters.
[^aeiou] Matches any single character not in the specified set of characters.
[0-9a-fA-F] Use of a hyphen (–) allows specification of contiguous character ranges.
\p{name} Matches any character in the named character class specified by {name}. Supported
names are Unicode groups and block ranges. For example, Ll, Nd, Z, IsGreek,
IsBoxDrawing.
\P{name} Matches text not included in groups and block ranges specified in {name}.
\w Matches any word character. Equivalent to the Unicode character categories [\p{Ll}\
p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]. If ECMAScript-compliant behavior is specified with
the ECMAScript option, \w is equivalent to [a-zA-Z_0-9].
\W Matches any nonword character. Equivalent to the Unicode categories [^\p{Ll}\
p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]. If ECMAScript-compliant behavior is specified with
the ECMAScript option, \W is equivalent to [^a-zA-Z_0-9].
\s Matches any white-space character. Equivalent to the Unicode character categories [\
f\n\r\t\v\x85\p{Z}]. If ECMAScript-compliant behavior is specified with the
ECMAScript option, \s is equivalent to [ \f\n\r\t\v].
\S Matches any non-white-space character. Equivalent to the Unicode character
categories [^\f\n\r\t\v\x85\p{Z}]. If ECMAScript-compliant behavior is specified with
the ECMAScript option, \S is equivalent to [^ \f\n\r\t\v].
\d Matches any decimal digit. Equivalent to \p{Nd} for Unicode and [0-9] for non-
Unicode, ECMAScript behavior.
\D Matches any nondigit. Equivalent to \P{Nd} for Unicode and [^0-9] for non-Unicode,
ECMAScript behavior.
 JS CheatSheet
Basics➤
On page script
<script type="text/javascript"> ...
</script>

Include external JS file


<script src="filename.js"></script>

Delay - 1 second timeout


setTimeout(function () {

}, 1000);

Functions
function addNumbers(a, b) {
return a + b; ;
}
x = addNumbers(1, 2);

Edit DOM element


document.getElementById("elementID").innerHTML = "Hello World!";

Output
console.log(a); // write to the browser console
document.write(a); // write to the HTML
alert(a); // output in an alert box
confirm("Really?"); // yes/no dialog, returns true/false depending on user click
prompt("Your age?","0"); // input dialog. Second argument is the initial value

Comments
/* Multi line
comment */
// One line

Loops↶
For Loop
for (var i = 0; i < 10; i++) {
document.write(i + ": " + i*3 + "<br />");
}
var sum = 0;
for (var i = 0; i < a.length; i++) {
sum + = a[i];
} // parsing an array
html = "";
for (var i of custOrder) {
html += "<li>" + i + "</li>";
}

While Loop
var i = 1; // initialize
while (i < 100) { // enters the cycle if statement is true
i *= 2; // increment to avoid infinite loop
document.write(i + ", "); // output
}
Do While Loop
var i = 1; // initialize
do { // enters cycle at least once
i *= 2; // increment to avoid infinite loop
document.write(i + ", "); // output
} while (i < 100) // repeats cycle if statement is true at the end

Break
for (var i = 0; i < 10; i++) {
if (i == 5) { break; } // stops and exits the cycle
document.write(i + ", "); // last output number is 4
}

Continue
for (var i = 0; i < 10; i++) {
if (i == 5) { continue; } // skips the rest of the cycle
document.write(i + ", "); // skips 5
}

If - Else⇵
if ((age >= 14) && (age < 19)) { // logical condition
status = "Eligible."; // executed if condition is true
} else { // else block is optional
status = "Not eligible."; // executed if condition is false
}

Switch Statement
switch (new Date().getDay()) { // input is current day
case 6: // if (day == 6)
text = "Saturday";
break;
case 0: // if (day == 0)
text = "Sunday";
break;
default: // else...
text = "Whatever";
}

Variablesx
var a; // variable
var b = "init"; // string
var c = "Hi" + " " + "Joe"; // = "Hi Joe"
var d = 1 + 2 + "3"; // = "33"
var e = [2,3,5,8]; // array
var f = false; // boolean
var g = /()/; // RegEx
var h = function(){}; // function object
const PI = 3.14; // constant
var a = 1, b = 2, c = a + b; // one line
let z = 'zzz'; // block scope local variable

Strict mode
"use strict"; // Use strict mode to write secure code
x = 1; // Throws an error because variable is not declared

Values
false, true // boolean
18, 3.14, 0b10011, 0xF6, NaN // number
"flower", 'John' // string
undefined, null , Infinity // special
Operators
a = b + c - d; // addition, substraction
a = b * (c / d); // multiplication, division
x = 100 % 48; // modulo. 100 / 48 remainder = 4
a++; b--; // postfix increment and decrement

Bitwise operators
& AND   5 & 1 (0101 & 0001) 1 (1)

| OR   5 | 1 (0101 | 0001) 5 (101)

~ NOT   ~ 5 (~0101) 10 (1010)

^ XOR   5 ^ 1 (0101 ^ 0001) 4 (100)

<< left shift   5 << 1 (0101 << 1) 10 (1010)

>> right shift   5 >> 1 (0101 >> 1) 2 (10)

>>> zero fill right shift   5 >>> 1 (0101 >>> 1) 2 (10)

Arithmetic
a * (b + c) // grouping
person.age // member
person[age] // member
!(a == b) // logical not
a != b // not equal
typeof a // type (number, object, function...)
x << 2 x >> 3 // minary shifting
a = b // assignment
a == b // equals
a != b // unequal
a === b // strict equal
a !== b // strict unequal
a < b a > b // less and greater than
a <= b a >= b // less or equal, greater or eq
a += b // a = a + b (works with - * %...)
a && b // logical and
a || b // logical or

Data Typesℜ
var age = 18; // number
var name = "Jane"; // string
var name = {first:"Jane", last:"Doe"}; // object
var truth = false; // boolean
var sheets = ["HTML","CSS","JS"]; // array
var a; typeof a; // undefined
var a = null; // value null

Objects
var student = { // object name
firstName:"Jane", // list of properties and values
lastName:"Doe",
age:18,
height:170,
fullName : function() { // object function
return this.firstName + " " + this.lastName;
}
};
student.age = 19; // setting value
student[age]++; // incrementing
name = student.fullName(); // call object function
Strings⊗
var abc = "abcdefghijklmnopqrstuvwxyz";
var esc = 'I don\'t \n know'; // \n new line
var len = abc.length; // string length
abc.indexOf("lmno"); // find substring, -1 if doesn't contain
abc.lastIndexOf("lmno"); // last occurance
abc.slice(3, 6); // cuts out "def", negative values count from behind
abc.replace("abc","123"); // find and replace, takes regular expressions
abc.toUpperCase(); // convert to upper case
abc.toLowerCase(); // convert to lower case
abc.concat(" ", str2); // abc + " " + str2
abc.charAt(2); // character at index: "c"
abc[2]; // unsafe, abc[2] = "C" doesn't work
abc.charCodeAt(2); // character code at index: "c" -> 99
abc.split(","); // splitting a string on commas gives an array
abc.split(""); // splitting on characters
128.toString(16); // number to hex(16), octal (8) or binary (2)

Events🕖
<button onclick="myFunction();">
Click here
</button>

Mouse
onclick, oncontextmenu, ondblclick, onmousedown, onmouseenter, onmouseleave,
onmousemove, onmouseover, onmouseout, onmouseup

Keyboard
onkeydown, onkeypress, onkeyup

Frame
onabort, onbeforeunload, onerror, onhashchange, onload, onpageshow, onpagehide, onresize, onscroll, onunload

Form
onblur, onchange, onfocus, onfocusin, onfocusout, oninput, oninvalid, onreset, onsearch, onselect, onsubmit

Drag
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop

Clipboard
oncopy, oncut, onpaste

Media
onabort, oncanplay, oncanplaythrough, ondurationchange, onended, onerror, onloadeddata, onloadedmetadata,
onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, onsuspend,
ontimeupdate, onvolumechange, onwaiting

Animation
animationend, animationiteration, animationstart

Miscellaneous
transitionend, onmessage, onmousewheel, ononline, onoffline, onpopstate, onshow, onstorage, ontoggle, onwheel,
ontouchcancel, ontouchend, ontouchmove, ontouchstart

Numbers and Math∑


var pi = 3.141;
pi.toFixed(0); // returns 3
pi.toFixed(2); // returns 3.14 - for working with money
pi.toPrecision(2) // returns 3.1
pi.valueOf(); // returns number
Number(true); // converts to number
Number(new Date()) // number of milliseconds since 1970
parseInt("3 months"); // returns the first number: 3
parseFloat("3.5 days"); // returns 3.5
Number.MAX_VALUE // largest possible JS number
Number.MIN_VALUE // smallest possible JS number
Number.NEGATIVE_INFINITY// -Infinity
Number.POSITIVE_INFINITY// Infinity

Math.
var pi = Math.PI; // 3.141592653589793
Math.round(4.4); // = 4 - rounded
Math.round(4.5); // = 5
Math.pow(2,8); // = 256 - 2 to the power of 8
Math.sqrt(49); // = 7 - square root
Math.abs(-3.14); // = 3.14 - absolute, positive value
Math.ceil(3.14); // = 4 - rounded up
Math.floor(3.99); // = 3 - rounded down
Math.sin(0); // = 0 - sine
Math.cos(Math.PI); // OTHERS: tan,atan,asin,acos,
Math.min(0, 3, -2, 2); // = -2 - the lowest value
Math.max(0, 3, -2, 2); // = 3 - the highest value
Math.log(1); // = 0 natural logarithm
Math.exp(1); // = 2.7182pow(E,x)
Math.random(); // random number between 0 and 1
Math.floor(Math.random() * 5) + 1; // random integer, from 1 to 5

Constants like Math.PI:


E, PI, SQRT2, SQRT1_2, LN2, LN10, LOG2E, Log10E

Dates📆
Sat Nov 26 2022 15:13:56 GMT+0530 (India Standard Time)
var d = new Date();
1669455836358 miliseconds passed since 1970
Number(d)
Date("2017-06-23"); // date declaration
Date("2017"); // is set to Jan 01
Date("2017-06-23T12:00:00-09:45"); // date - time YYYY-MM-DDTHH:MM:SSZ
Date("June 23 2017"); // long date format
Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)"); // time zone

Get Times
var d = new Date();
a = d.getDay(); // getting the weekday

getDate(); // day as a number (1-31)


getDay(); // weekday as a number (0-6)
getFullYear(); // four digit year (yyyy)
getHours(); // hour (0-23)
getMilliseconds(); // milliseconds (0-999)
getMinutes(); // minutes (0-59)
getMonth(); // month (0-11)
getSeconds(); // seconds (0-59)
getTime(); // milliseconds since 1970

Setting part of a date


var d = new Date();
d.setDate(d.getDate() + 7); // adds a week to a date
setDate(); // day as a number (1-31)
setFullYear(); // year (optionally month and day)
setHours(); // hour (0-23)
setMilliseconds(); // milliseconds (0-999)
setMinutes(); // minutes (0-59)
setMonth(); // month (0-11)
setSeconds(); // seconds (0-59)
setTime(); // milliseconds since 1970)

Arrays≡
var dogs = ["Bulldog", "Beagle", "Labrador"];
var dogs = new Array("Bulldog", "Beagle", "Labrador"); // declaration

alert(dogs[1]); // access value at index, first item being [0]


dogs[0] = "Bull Terier"; // change the first item

for (var i = 0; i < dogs.length; i++) { // parsing with array.length


console.log(dogs[i]);
}

Methods
dogs.toString(); // convert to string: results
"Bulldog,Beagle,Labrador"
dogs.join(" * "); // join: "Bulldog * Beagle * Labrador"
dogs.pop(); // remove last element
dogs.push("Chihuahua"); // add new element to the end
dogs[dogs.length] = "Chihuahua"; // the same as push
dogs.shift(); // remove first element
dogs.unshift("Chihuahua"); // add new element to the beginning
delete dogs[0]; // change element to undefined (not recommended)
dogs.splice(2, 0, "Pug", "Boxer"); // add elements (where, how many to remove,
element list)
var animals = dogs.concat(cats,birds); // join two arrays (dogs followed by cats and
birds)
dogs.slice(1,4); // elements from [1] to [4-1]
dogs.sort(); // sort string alphabetically
dogs.reverse(); // sort string in descending order
x.sort(function(a, b){return a - b}); // numeric sort
x.sort(function(a, b){return b - a}); // numeric descending sort
highest = x[0]; // first item in sorted array is the lowest (or
highest) value
x.sort(function(a, b){return 0.5 - Math.random()}); // random order sort

concat, copyWithin, every, fill, filter, find, findIndex, forEach, indexOf, isArray, join, lastIndexOf, map, pop, push, reduce,
reduceRight, reverse, shift, slice, some, sort, splice, toString, unshift, valueOf

Global Functions()
eval(); // executes a string as if it was script code
String(23); // return string from number
(23).toString(); // return string from number
Number("23"); // return number from string
decodeURI(enc); // decode URI. Result: "my page.asp"
encodeURI(uri); // encode URI. Result: "my%page.asp"
decodeURIComponent(enc); // decode a URI component
encodeURIComponent(uri); // encode a URI component
isFinite(); // is variable a finite, legal number
isNaN(); // is variable an illegal number
parseFloat(); // returns floating point number of string
parseInt(); // parses a string and returns an integer
Regular Expressions\n
var a = str.search(/CheatSheet/i);

Modifiers
iperform case-insensitive matching

gperform a global match

mperform multiline matching

Patterns
\ Escape character \d find a digit
\s find a whitespace character \b find match at beginning or end of a word
n+ contains at least one n n* contains zero or more occurrences of n
n? contains zero or one occurrences of n ^ Start of string
$ End of string \ uxxxx find the Unicode character
. Any single character (a|b) a or b
(...) Group section [abc] In range (a, b or c)
[0-9] any of the digits between the brackets [^abc] Not in range
\s White space a? Zero or one of a
a* Zero or more of a a*? Zero or more, ungreedy
a+ One or more of a a+? One or more, ungreedy
a{2} Exactly 2 of a a{2,} 2 or more of a
a{,5} Up to 5 of a a{2,5} 2 to 5 of a
a{2,5}? 2 to 5 of a, ungreedy [:punct:] Any punctuation symbol
[:space:] Any space character [:blank:] Space or tab

Errors⚠
try { // block of code to try
undefinedFunction();
}
catch(err) { // block to handle errors
console.log(err.message);
}

Throw error
throw "My error message"; // throw a text

Input validation
var x = document.getElementById("mynum").value; // get input value
try {
if(x == "") throw "empty"; // error cases
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x > 10) throw "too high";
}
catch(err) { // if there's an error
document.write("Input is " + err); // output error
console.error(err); // write the error in console
}
finally {
document.write("</br />Done"); // executed regardless of the try / catch
result
}
Error name values
RangeErrorA number is "out of range"

ReferenceErrorAn illegal reference has occurred

SyntaxErrorA syntax error has occurred

TypeErrorA type error has occurred

URIErrorAn encodeURI() error has occurred

JSONj
var str = '{"names":[' + // crate JSON object
'{"first":"Hakuna","lastN":"Matata" },' +
'{"first":"Jane","lastN":"Doe" },' +
'{"first":"Air","last":"Jordan" }]}';
obj = JSON.parse(str); // parse
document.write(obj.names[1].first); // access

Send
var myObj = { "name":"Jane", "age":18, "city":"Chicago" }; // create object
var myJSON = JSON.stringify(myObj); // stringify
window.location = "demo.php?x=" + myJSON; // send to php

Storing and retrieving


myObj = { "name":"Jane", "age":18, "city":"Chicago" };
myJSON = JSON.stringify(myObj); // storing data
localStorage.setItem("testJSON", myJSON);
text = localStorage.getItem("testJSON"); // retrieving data
obj = JSON.parse(text);
document.write(obj.name);

PromisesÞ
function sum (a, b) {
return Promise(function (resolve, reject) {
setTimeout(function () { // send the response
after 1 second
if (typeof a !== "number" || typeof b !== "number") { // testing input types
return reject(new TypeError("Inputs must be numbers"));
}
resolve(a + b);
}, 1000);
});
}
var myPromise = sum(10, 5);
myPromsise.then(function (result) {
document.write(" 10 + 5: ", result);
return sum(null, "foo"); // Invalid data and return another promise
}).then(function () { // Won't be called because of the error
}).catch(function (err) { // The catch handler is called instead, after
another second
console.error(err); // => Please provide two numbers to sum.
});

States
pending, fulfilled, rejected

Properties
Promise.length, Promise.prototype

Methods
Promise.all(iterable), Promise.race(iterable), Promise.reject(reason), Promise.resolve(value)
jQuery CheatSheet
Basics
Include
Download
<script src="https://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

Syntax
$(document).ready(function(){
$(".demo").click(function(){
$(this).hide(200);
});
});
$(function(){
// Short Document Ready
});

Each
$(".demo").each(function() { // parse each .demo element
document.write($(this).text() + "\n"); // output their text
});

Trigger
$("a#mylink").trigger("click"); // triggers event on an element

noConflict
var jq = $.noConflict(); // avoid conflict with other frameworks also using
the dollar sign
jq(document).ready(function(){
jq("#demo").text("Hello World!");
});

Selectors
$("*") // all elements
$("p.demo") // <p> elements with class="demo"
$("p:first") // the first <p> element
$("p span") // span, descendant of p
$("p > span") // span, direct child of p
$("p + span") // span immediately proceeded by a p
$("p ~ span") // strong element proceeded by p
$("ul li:first") // the first <li> element of the first <ul>
$("ul li:first-child") // the first <li> element of every <ul>
$("ul li:nth-child(3)") // third child
$("[href]") // any element with an href attribute
$("a[target='_blank']") // <a> elements with a target "_blank" attribute
$("a[target!='_blank']") // <a> elements with a target attribute value other than
"_blank"
$(":input") // all form elements
$(":button") // <button> and <input> elements of type="button"
$("tr:even") // even <tr> elements
$("tr:odd") // odd <tr> elements
$("span:parent") // element which has child element
$("span:contains('demo')") // element conaining the specified text

Actions
$(selector).action()
$(this).hide() // the current element
$("div").hide() // all <div> elements
$(".demo").hide() // all elements with class="demo"
$("#demo").hide() // the element with id="demo"

Events
$(".demo").click(function(){
$(this).hide(200);
});

Mouse
scroll, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, load, resize,
scroll, unload, error

Keyboard
keydown, keypress, keyup

Form
submit, change, focus, blur

DOM Element
blur, focus, focusin, focusout, change, select, submit

Browser
load, resize, scroll, unload, error

.bind()
$(document).ready(function() { // attach a handler to an event for the
elements
$("#demo").bind('blur', function(e) {
//dom event fired
});
});

Effects
Hide / Show
$("#demo").hide(); // sets to display: none
$("#demo").show(200); // shows hidden elemnt with animation (speed)
$("#demo").toggle(); // toggle between show and hide

$( "#element" ).hide( "slow", function() { // hide with callback function


console.log( "Animation complete." );
});

Fade
fadeIn, fadeOut, fadeToggle, fadeTo
$("#demo").fadeIn(); // fade in a hidden element
$("#demo").fadeOut(300); // fade out
$("#demo").fadeToggle("slow"); // toggle between fadeIn and hadeOut
$("#demo").fadeTo("slow", 0.25); // fades to 0.25 opacity

Slide
slideDown, slideUp, slideToggle
$("#demo").slideDown();
$("#demo").slideUp("slow");
$("#demo").slideToggle();

Animate
$(selector).animate({params},speed,callback);
$("div").animate({
opacity: '0.5',
left: '200px',
height: '200px'
});

stop() Method
$("#demo").stop();
$('#demo').mouseleave(function(event) { // hover end
$('.tab').stop().animate({ // stop() method
opacity : '0.5',
marginTop: '10px'
}, 500, function() { // animation complete
$('#demo').removeClass('hovered'); // callback function
});
});
$('#demo').mouseover(function(event) { // hover begin
$('.tab').stop().animate({ // stop() method
opacity : '1',
marginTop: '0px'
}, 300, function() { // animation complete
$('#demo').addClass('hovered'); // callback function
});
});

Chaining
$("#demo").css("backgroundColor", "green").slideUp(500).slideDown(500);

DOM Manipulation
Content
$("#demo").text(); // returns text content
$("#demo").html(); // returns content, including HTML markup
$("#demo").val(); // returns field value
$("#demo").html('Hey <em>yo</em>'); // sets HTML content

Attributes
$("#link").attr("href"); // get an attribute
$("#link").attr("href",'https://htmlg.com'); // set attribute
$("#link").attr({
"href" : "https://htmlg.com", // setting multiple attributes
"title" : "HTML Editor"
});
$("#link").attr("href", function(i, origValue){
return origValue + "/help"; // callback function gets and changes the
attribute
});

Add
$(".demo").prepend("Yo!"); // adds content at the beginning in the selected
elements
$(".demo").append("<em>Hey!</em>"); // adds content at the end in the selected elements
$(".demo").before("Cheers"); // adds content before the selected elements
$(".demo").after("<em>Peace</em>"); // adds content after the selected elements

Remove
$("#demo").remove(); // removes the selected element
$("#demo").empty(); // removes children
$("div").remove(".cl1, .cl2"); // removes divs with the listed classes

Classes
$("#demo").addClass("big red"); // add class
$("h1, p").removeClass("red"); // remove class
$("#demo").toggleClass("big"); // toggle between adding and removing
CSS
$("#demo").css("background-color"); // returns CSS value
$("#demo").css("color", "blue"); // sets CSS rule
$("#demo").css({"color": "blue", "font-size": "20px"}); // sets multiple CSS properties

Dimensions
width, height, innerWidth, innerHeight, outerWidth, outerHeight
inner  - includes padding
outer - includes padding and border

Traversing
$("#demo").parent(); // accessing direct parent
$("span").parent().hide(); // changing parent color
$("#demo").parents(); // all ancestors of the element
$("#demo").parentsUntil("#demo2"); // all ancestors between two - demo is inside demo2
$("#demo").children(); // all direct children
$("#demo").children(".first"); // all direct children having a specified class
$("#demo").find("span"); // all span elements inside #demo
$("#demo").find("*"); // all descendants
$("#demo").siblings("span"); // span siblings of #demo
$("#demo").next(); // the next sibling
$("p").nextAll(); // all next siblings
$("#demo").nextUntil("#demo2"); // siblings between two arguments
$("#demo").prev(); // the previous sibling
$("p").prevAll(); // all previous siblings
$("#demo").prevUntil("#demo2"); // previous siblings between two arguments

Filtering
$("span strong").first(); // first strong in first span
$("span strong").last(); // last strong in last span
$("div").eq(9); // element with a specific index
$("div").filter(".big"); // all div elements with .big class
$("div").not(".big"); // opposite of filter

Ajax
$("#demo").load("file.txt h1.main"); // returns the h1 tag
in the text file
$("#demo").load("file.txt", function(responseTxt, statusTxt, xhr){ // callback function
if(statusTxt == "success") {
document.write("Content loaded successfully!");
} else {
document.write("Error: " + xhr.status + ": " + xhr.statusText);
}
});

$.get()
$.get("demo.asp", function(data, status){ //$.get(URL,callback);
document.write("Data: " + data + "\nStatus: " + status);
});

$.post()
$.post("demo.asp", // send HTTP POST request to a page and get the answer
{
name: "John", // send data
age: 30
},
function(data, status){ //retreive response
console.log("Data: " + data + "\nStatus: " + status);
});

You might also like