mvc and razor - doc. v1.2

33
MVC and Razor By Naji El Kotob, MCT Version 1.2 - DRAFT

Upload: naji-el-kotob

Post on 22-Jan-2018

4.314 views

Category:

Education


0 download

TRANSCRIPT

Page 1: MVC and Razor - Doc. v1.2

MVC and RazorBy Naji El Kotob, MCT

Version 1.2 - DRAFT

Page 2: MVC and Razor - Doc. v1.2

Razor Layout

About MVC

Razor

Why Razor

RenderBody

RenderPage

RenderSection

Styles.Render/Scripts.Render

_ViewStart file

HTML Helpers

Partial View

Type of Returns

Page 3: MVC and Razor - Doc. v1.2

MVC

Page 4: MVC and Razor - Doc. v1.2

MVC

The MVC separation helps you manage complex applications, because you can

focus on one aspect a time. For example, you can focus on the view without

depending on the business logic. It also makes it easier to test an application.

The MVC separation also simplifies group development. Different developers

can work on the view, the controller logic, and the business logic in parallel.

Page 5: MVC and Razor - Doc. v1.2

MVC - Model

The Model is the part of the application that handles the logic for the

application data.

Often model objects retrieve data (and store data) from a database.

Page 6: MVC and Razor - Doc. v1.2

MVC - View

The View is the parts of the application that handles the display of the data.

Most often the views are created from the model data.

Page 7: MVC and Razor - Doc. v1.2

MVC - Controller

The Controller is the part of the application that handles user interaction.

Typically controllers read data from a view, control user input, and send input

data to the model.

MVC requires the name of all controller files to end with “Controller“ e.g.

HomeController

Page 8: MVC and Razor - Doc. v1.2

Razor

Page 9: MVC and Razor - Doc. v1.2

Razor

“Razor” is a new view engine for ASP.NET

Page 10: MVC and Razor - Doc. v1.2

Why Razor

Compact, Expressive, and Fluid

Is not a new language

Easy to Learn

Works with any Text Editor

Has great Intellisense (VS)

Unit Testable

Page 11: MVC and Razor - Doc. v1.2

RenderBody

The RenderBody method resides in Layout page

{/Views/Shared/_Layout.vbhtml}.

There can only be one RenderBody method per Layout page (Calling it twice will

generate an exception „The "RenderBody" method has already been called‟).

The RenderBody method indicates where view templates that are based on

this master layout file should fill-in the body content.

Page 12: MVC and Razor - Doc. v1.2

RenderPage

Layout pages can also contain content that can be filled by other pages on

disk. This is achieved by using the RenderPage method. This method

RenderPage takes two parameters, the physical location of the file and an

optional array of objects that can be passed into the calling page.

E.g. Add a new vbhtml/cshtml file to the Shared folder and call it

_Header.cshtml. Prefix it with an underscore to block any calling to it outside

of RenderPage.

Tip: ASP.NET will not serve pages beginning with an underscore. E.g.

_Header.vbhtml page.

Page 13: MVC and Razor - Doc. v1.2

RenderSection

A layout page can contain multiple sections. RenderSection runs code blocks

in the content pages.

Page 14: MVC and Razor - Doc. v1.2

Styles.Render/Scripts.Render

Styles.Render/Scripts.Render loads the css and js specified in

BundleConfig.vb/.cs placed in App_Start folder.

Page 15: MVC and Razor - Doc. v1.2

_ViewStart

The _ViewStart file can be used to define common view code that you want to

execute at the start of each View‟s rendering.

For example, we could write code like below within our _ViewStart.vbhtml/cshtml

file to programmatically set the Layout property for each View to be the

_Layout.vbhtml/cshtml file by default:

Page 16: MVC and Razor - Doc. v1.2

HTML Helpers

ASP.NET MVC providers a number of HtmlHelper methods for rendering

markup based on the view model.

Page 18: MVC and Razor - Doc. v1.2

Html Helper Markup

Html.LabelFor <label … >…</label>

Html.HiddenFor <input type="hidden" … />

Html.PasswordFor <input type="password" … />

Html.EditorFor

(DataType.Password)

<input class="text-box single-line password" type="password" … />

Html.CheckBoxFor <input type="check" … />

Html.RadioButtonFor <input type="radio" … />

Html.TextBoxFor <input type="text" … />

Html.EditorFor

(default)

<input class="text-box single-line" type="text" … />

Html.TextAreaFor <textarea … />

Html.EditorFor

(DataType.MultiLineText)

<textarea class="text-box multi-line" … />

Html.DropDownListFor <select …>…</select>

Html.ListBoxFor <select multiple="multiple">…</select>

Html.EditorFor

(bool)

<input type="checkbox" class="check-box" … />

Html.EditorFor

(bool?)

<select class="list-box tri-state" …> <option value="" … /> <option

value="true" … /> <option value="false" … /> </select>

Page 19: MVC and Razor - Doc. v1.2

Html.ValidationMessageFor <span class="field-validation-valid">…</span> or <span class="field-

validation-error">…</span>

The classes "input-validation-valid" or "input-validation-error" are included

in form input elements with associated validations.

Html.ValidationSummaryFor <div class="validation-summary-error"> <span>message</span> <ul>…</ul>

</div>

Html.EditorFor

(complex type)

<div class="editor-label"> <%: Html.LabelFor(…) %> </div> <div

class="editor-field"> <%: Html.EditorFor(…) %> <%: Html.ValidatorFor(…) %>

</div>

Html.EditorforModel Same as EditorFor using the implicit view model.

Html.DisplayFor

(default)

Value

Html.DisplayFor

(bool)

<input type="checkbox" class="check-box" disabled="disabled" … />

Html.DisplayFor

(bool?)

Same as EditorFor when rendering a bool? type, with addition of

disabled="disabled" attribute.

Html.DisplayFor

(complex type)

<div class="display-label"> <%: Html.LabelFor(…) %> </div> <div

class="display-field"> <%: Html.DisplayFor(…) %> </div>

Page 20: MVC and Razor - Doc. v1.2

Demo

<form action="/Person/Edit" method="post">

<input id="EmployeeId" name="EmployeeId" type="hidden" value="1" />

<div>

<label for="LastName">Last Name</label>

<input id="LastName" name="LastName" type="text" value="Davolio" /> </div>

<div>

<label for="FirstName">First Name</label>

<input id="FirstName" name="FirstName" type="text" value="Nancy" /> </div>

<div>

<label for="BirthDate">BirthDate</label>

<input name="BirthDate" type="text" value="12/8/1948" />

</div>

<input type="submit" value="Save" />

</form>

@using (Html.BeginForm()) {

@Html.HiddenFor(model => model.EmployeeId)

<div>

@Html.LabelFor(model => model.LastName)

@Html.EditorFor(model => model.LastName)

</div>

<div>

@Html.LabelFor(model => model.FirstName)

@Html.EditorFor(model => model.FirstName)

</div>

<div>

@Html.LabelFor(model => model.BirthDate)

@Html.EditorFor(model => model.BirthDate)

</div>

<input type="submit" value="Save" />

}

Page 21: MVC and Razor - Doc. v1.2

Validation

The ValidationSummary helper method renders a list of validation errors, if any

are found. In addition, the ValidationMessage helper method renders a validation

error message next to each form field for which an error is found.

<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

<% Using Html.BeginForm()%>

<fieldset>

<legend>Fields</legend>

<p>

<label for="Name">Name:</label>

<%= Html.TextBox("Name") %> Required

<%= Html.ValidationMessage("Name", "*") %>

</p>

Page 22: MVC and Razor - Doc. v1.2

Partial View

Page 23: MVC and Razor - Doc. v1.2

Partial View

A Partial View is a reusable fragment of content and code that can be

embedded in another view and improves the usability of a site, while

reducing duplicate code.

Web User Control / Web Server Control (Web Forms) = Partial views (MVC)

A simple use of the partial views is to use it to display social bookmarking

icons across multiple pages.

Page 24: MVC and Razor - Doc. v1.2

Views vs. Partial View

A View when rendered produces a full HTML document, whereas a partial

view when rendered produces a fragment of HTML.

A partial view does not specify the layout.

Page 25: MVC and Razor - Doc. v1.2

Creating Partial Views

In order to create a partial view:

Right click the /Views/Shared folder > Add > View. Type a View Name, type or

choose a class from the Model class and check the Create as a partial view option,

as shown below

Page 26: MVC and Razor - Doc. v1.2

Inserting Partial Views

Partial Views can be inserted by calling the Partial or RenderPartial helper method. The difference between the two is that the Partial helper renders a partial view into a string whereas RenderPartial method writes directly to the response stream instead of returning a string.

E.g.

So the difference between Partial and RenderPartial is in the return value. Partial returns result as MvcHtmlString and uses StringWriter to render view, and RenderPartial renders the view directly with no return value.

One more thing to remember while using this two methods if you are using Razor. You can use @Html.Partial("_PartialView", Model) - and it works fine, but you can‟t use @Html.RenderPartial("_PartialView", Model) - since it returns no result, and @statement syntax can be used with method, that returns some result. So in this case use RenderPartial like this: @{Html.RenderPartial("_PartialView", Model);}

Page 27: MVC and Razor - Doc. v1.2

Partial View / AJAX

You can use jQuery to make an AJAX request and load a Partial View into a View.

E.g. Suppose there‟s a div element called „div-sociallinks‟

$('#div-sociallinks').html('This is the new content!');

Or

$.ajax({

url: „/socialLinksPartialView/index/‟,

type: 'GET',

cache: false,

success: function (result) {

$('#div-sociallinks').html(result);

}

}

$('#div-sociallinks').html('This is the new content!');

$('#div-sociallinks').html('This is the new content!');

$('#div-sociallinks').html('This is the new content!');

Page 28: MVC and Razor - Doc. v1.2

Type of Returns

Page 29: MVC and Razor - Doc. v1.2
Page 30: MVC and Razor - Doc. v1.2
Page 31: MVC and Razor - Doc. v1.2

Feedback

Naji El Kotob, [email protected]

Thank You

Page 32: MVC and Razor - Doc. v1.2

References

http://www.dotnetcurry.com/ShowArticle.aspx?ID=636

http://www.dotnetspeaks.com/DisplayArticle.aspx?ID=241

http://www.em64t.net/2010/12/razor-html-renderpartial-vs-html-partial-html-

renderaction-vs-html-action-what-one-should-use/

http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-

sections-with-razor.aspx

http://www.w3schools.com/aspnet/mvc_htmlhelpers.asp

http://rachelappel.com/razor/partial-views-in-asp-net-mvc-3-w-the-razor-view-

engine/

http://weblogs.asp.net/scottgu/archive/2010/10/22/asp-net-mvc-3-layouts.aspx

Page 33: MVC and Razor - Doc. v1.2

References (Cont.)

http://www.gxclarke.org/2010/10/markup-rendered-by-aspnet-mvc-html.html

http://www.devcurry.com/2012/04/partial-views-in-aspnet-mvc-3.html

http://msdn.microsoft.com/en-us/library/dd381412(v=vs.108).aspx