loading...

Cheatsheet for Razor Page

ssmak profile image Steve Mak Updated on ・2 min read

Keywords

View

ViewData | ViewBag | TempData | @page | @model
@addTagHelper | @removeTagHelper | @Html.AntiForgeryToken()
RenderBody | RenderSection
Html.BeginForm("<Action>", "<Controller>")
Html.RenderPartialAsync("<Name of file with extension .cshtml>")
Html.DisplayNameFor(model => model.ReleaseDate)
Html.DisplayFor(model => model.Title)

Model

ViewData | ViewBag | TempData | View() | Page()
IActionResult | ModelState | RedirectToPage

Data Annotation

Reference: https://dev.to/ssmak/test-2fl0

[BindProperty] | [BindProperty(Name = "Name123")] | [BindProperty(SupportsGet = true)]
[Key] | [DisplayName] | [Column] | [StringLength], [Range], [RegularExpression]
[HttpPost] | [ValidateAntiForgeryToken]

Tag Helper

Reference: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/?view=aspnetcore-3.1

asp-page | asp-page-handler | asp-route-<> | asp-action | asp-controller
asp-for | asp-items

/*
Use with <div>
e.g.
<div asp-validation-summary="All">
    <span>Please correct the following errors</span>
</div>
*/
asp-validation-summary

/*
Use with <span>
e.g
<span asp-validation-for="FirstName" class="myclass"></span>
*/
asp-validation-for

/*
Import partial view
*/
<partial name="_MenuPartial" />

/*
Import view component
*/
<vc:priority-list max-priority="2" is-done="false">
</vc:priority-list>

Html Helper

Html.DisplayNameFor | Html.DisplayFor | Html.RenderPartialAsync
Html.Partial

Code References

Form validation

<!-- asp-validation-summary, asp-for, asp-validation-for -->
<form method="post">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <input type="hidden" asp-for="Products.ProductId" />
    <div class="form-group">
        <label asp-for="Products.ProductName" class="control-label"></label>
        <input asp-for="Products.ProductName" class="form-control" />
        <span asp-validation-for="Products.ProductName" class="text-danger"></span>
    </div>
</form>

Import external JavaScript file

@* @section, Scripts, Html.RenderPartialAsync  *@
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Custom tag helper

public class EmailTagHelper : TagHelper
{
    private const string EmailDomain = "contoso.com";

    // Can be passed via <email mail-to="..." />. 
    // Pascal case gets translated into lower-kebab-case.
    public string MailTo { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "a";    // Replaces <email> with <a> tag

        var address = MailTo + "@" + EmailDomain;
        output.Attributes.SetAttribute("href", "mailto:" + address);
        output.Content.SetContent(address);
    }
}

Discussion

pic
Editor guide