Razor Templates
- used to produce HTML with cshtml extension.
- templates that consist of HTML markups.
--------------------------------------------
@ - C# code on cshtml, similar to Response.Write
Razor will automatically HTML encode any output sent through the @sign to help prevent cross site scripting attack (XSS)
--------------------------------------------
Foreach statement - allows us to iterate through the model pulling out one item at a time
@foreach (var item in Model){
<tr><td>
@:Review => tells Razor that this is a literal text, and not part of C# code expression
@item.Rating => implicit code expression in Razor
@(item.Rating / 10) => (ex: you want to divide by 10) explicit code expression with parenthesis
R@(item.Rating) => if you want to prefix the value with R.
@@Test => to escape the @sign, and output the text literally. intended to do for a Twitter handle.
@Html.DisplayFor(modelItem => item.Rating) => usual
</td></tr>
<tr><td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id}) => text, action, ID wrapped up in anonymous object
</td></tr>
}
On the controller:
public ActionResult Edit(int id)
{
var review = _reviews.Single(r => r.Id == id); => give me a single object out of this "_reviews" collection that matches this criteria.
return View(review);
}
--------------------------------------------
Code Blocks - code inside of the block is going to execute. It's not going to have its expressions evaluated and written to the client. It simply executes and produces side effects.
You can also declare a variable and assign a value.
@{
ViewBag.Title = "Index";
var firstReview = Model.First();
}
@firstReview.Name
--------------------------------------------
@Html.Raw(item.City) - displays the text or value as is. Not encoded.
--------------------------------------------
Comments use @* and *@
You can comment a section of code by selecting the code and hitting Ctrl + K, Ctrl + C
To automatically reformat your code, to fit right into the file or align property Ctrl + K , Ctrl + D
--------------------------------------------
File extensions:
.cshtml => C# Razor
.vbhtml => VB Razor
.aspx, .ascx => Web Forms (legacy)
--------------------------------------------
Layout with Razor
Views > Shared > _layout.cshtml
The underscore is just a convention to identify views that are not primary content views like the index view that we wrote.
This is just another Razor view. It has literal text that can have C# code expressions, and can have code blocks, where you typically have your doctype, and where you want to have your head tag, and you typically have a definition for the body element. Any changes will be reflected across the entire application. This is the only layout view we'll be using. You can have multiple layout files, but only 1 can be used by the application.
<!DOCTYPE html>
Use inherited methods to specify content areas
RenderBody
RenderSection - optional, provides a content view like index.cshtml
Views > _ViewStart.cshtml = determines the view to be used by MVC. This has the ability to execute this code before my view starts rendering and it sets this property.
@{
Layout = "~Views/Shared/_Layout.cshtml";
}
Anything you put in that code block at the top will be able to execute before the view does.
If you want to have another layout for another folder, just create a new _ViewStart.cshtml on the folder, and define the layout file to be used.
Set Layout to null if you don't want to use a layout page.
@{
Layout = null; => can also be set on the cshtml file.
}
@RenderSection("featured", required: false) => not a required section, which means a content view can have this section that cannot ...
in index.cshtml file:
@section featured{
We are showing the latest @Model.Count() reviews
}
--------------------------------------------
HTML Helpers
- Make it easy to create small blocks of HTML. To keep views simple.
HTML is a property of the ViewPage base class.
- Create inputs
- Create links
- Create forms
@Html.BeginForm()
- equivalent to <form action ="Reviews/Edits/3 <something else>" method = "post"> post means to go to the URL where we came from when the user clicks on the button.
@Html.HiddenFor
<input type="hidden" .../>
@Html.LabelFor(model => model.Name)
- great for accessibility
<label for = "Name">Name</label>
for is equivalent to the name of the property.
@Html.EditorFor(model => model.Name)
- saying "I want an editor for this property."
<input class="<name for the CSS class>" id = "Name" type = "text" .../>
type can be a text or number
@Html.ValidationMessageFor(model => model.Country)
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var review = _reviews.Single(r => r.Id == id);
if (TryUpdateModel(review)) ==> to go through a process known as model binding. Model binding happens anytime you even have a parameter in an action method. This relies on the names of the properties to match up data with what needs to get pushed into the model.
{
//part where the data should be saved into the database. (but on this sample - redirect to another page where user can view the changed result)
return RedirectToAction("Index");
}
return View(review);
}
--------------------------------------------
Partial Views
- Render a portion of a page
- Still .cshtml files and can still be strongly typed, still has a model that it can work against
- Allow you to put HTML on C# code into a file that you can reuse across multiple other views.
- To simplify a view
On the sample, the partial view is named _Review.cshtml.
When you select "Create as a partial view" on the Add View dialog box, it won't automatically add a code block at the top of the view to set the page title.
Note that this will be available only to other views that are in the same folder. If this is placed in the Shared folder, it would be available anywhere in the application.
Sample:
@model OdeToFood.Models.RestaurantReview
<div class="review">
<h4>@Model.Name</h4>
<span>@Model.Rating</span>
<span class="right">@Html.ActionLinkEdit", "Edit", new {id=Model.Id})</span>
</div>
On your main view:
@foreach var item in Model)
{
@Html.Partial("_Review", item) ==> no need to specify the file extension
==> model to be passed
}
<p>
@Html.ActionLink("Create New", "Create")
</p>
--------------------------------------------
@Html.Action vs @Html.Partial
_Layout.cshtml ==> executes for every page in the application.
To show a view on every page of the application through Layout view:
<div>
@Html.Action("BestReview", "Reviews") ==> sets up a sub request inside of this primary MVC request that can go out and call another controller action
==> action
==> Reviews controller
</div>
On the ReviewsController, create a new BestReview action.
[ChildActionOnly] ===> attribute that prevents the action from being called directly using a HTTP request. Can be accessed by calling it as a child request.
public ActionResult BestReview()
{
var bestReview = from r in _reviews
orderby r.Rating descending
select r;
return PartialView("_Review", bestReview.First()); ==> PartialViewResult is a type of ActionResult
===> pass the partial view created. no extension needed here.
===> pass the first review that we picked up
}
@Html.Partial - which allows you to simplify a view and reuse HTML.
@Html.Action - which allows you to set up a completely independent subrequest that builds its own model and renders its own PartialView.
No comments:
Post a Comment