Lessons in this course (10)

4. Razor views, layouts, HTML helpers and partial views

Basic★ Must knowLesson 4 of 10
cshtml
@model ShopMvc.Models.ProductEditModel
@{
    ViewBag.Title = "Create product";
}
<h2>@ViewBag.Title</h2>

@using (Html.BeginForm("Create", "Products", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    @Html.LabelFor(m => m.Name)
    @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.Name)

    @Html.DropDownListFor(m => m.CategoryId, Model.Categories, "-- choose --")
    @Html.EditorFor(m => m.Price)

    <button type="submit" class="btn btn-primary">Save</button>
}

@Html.Partial("_ProductTips")                       @* partial view, uses current model unless passed *@
@Html.Action("TopSellers", "Products")               @* child action: runs a controller action and renders its result *@

@section scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
cshtml
@* Views/Shared/_Layout.cshtml *@
<!DOCTYPE html>
<html>
<head><title>@ViewBag.Title - Divakar Shop</title>@Styles.Render("~/Content/css")</head>
<body>
    @Html.Partial("_LoginPartial")
    <div class="container">@RenderBody()</div>
    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>

Razor basics: @expression (HTML-encoded automatically), @{ code block }, @if/@foreach, @Html.Raw(x) (no encoding — dangerous), @* comment *@, @: text line. Views are compiled into classes deriving from WebViewPage<TModel> the first time they are requested (or at build with MvcBuildViews).

Partial view vs child action: a partial renders a template with data you pass; a child action (Html.Action) runs a full controller action (with its own data access and filters) — useful for widgets like a cart summary on every page. (ASP.NET Core replaces child actions with view components.)

Display/editor templates: Views/Shared/EditorTemplates/DateTime.cshtml customises Html.EditorFor for every DateTime property.