ASP.NET MVC 3 - Presentare i dati nella View

Post on 30-Nov-2014

1.713 views 0 download

description

Mostrare i dati all'utente nelle View con Razor

Transcript of ASP.NET MVC 3 - Presentare i dati nella View

ASP.NET

Sviluppo applicazioni web e linguaggio HTML

LEZIONE 05

Model View Controller

Model

Con le View

mostriamo i dati

all’utente

Quali dati?

Quelli del model …

Quelli del model …

Visualizziamo in homepage il numero totale di

post e commenti utilizzando il DbContext

Quelli del model …

Visualizziamo in homepage il numero totale di post

e commenti utilizzando il DbContext e LINQ to Entities

int totalPosts = 0, totalComments = 0;

using (var db = new BlogContext())

{

totalComments = db.Comments.Count();

totalPosts = (from p in db.Posts

where p.IsPublished

select p).Count();

}

… e nella vista i dati

come li trasportiamo?

In una valigia, ovviamente …

ViewBag

dynamic al quale

possiamo assegnare

proprietà arbitrarie

ViewBag

dynamic al quale

possiamo assegnare

proprietà arbitrarie

ViewBag.TotalPosts

int totalPosts = 0, totalComments = 0;

using (var db = new BlogContext())

{

totalComments = db.Comments.Count();

totalPosts = (from p in db.Posts

where p.IsPublished

select p).Count();

}

ViewBag.TotalPosts = totalPosts;

ViewBag.TotalComments = totalComments;

ViewBag.TotalPosts

Il ViewBag permette di rendere dinamico

l’accesso ad un dizionario, il ViewData

In realtà …

int totalPosts = 0, totalComments = 0;

using (var db = new BlogContext())

{

totalComments = db.Comments.Count();

totalPosts = (from p in db.Posts

where p.IsPublished

select p).Count();

}

ViewBag.TotalPosts = totalPosts;

ViewData[“TotalComments”] = totalComments;

ViewBag.TotalPosts

ma vediamo come

nella vista i dati del

model si mescolano al

codice html …

ma vediamo come

nella vista i dati del

model si mescolano al

codice html …

Questa sintassi in esecuzione viene

interpretata da un View Engine

Questa sintassi in esecuzione viene

interpretata da un View Engine, che

ha il compito di tradurre il codice

sottostante nell’html da inviare al

browser.

Questa sintassi in esecuzione viene

interpretata da un View Engine, che

ha il compito di tradurre il codice

sottostante nell’html da inviare al

browser. Il View Engine in questione

si chiama Razor

Mostriamo in home gli ultimi post:

Mostriamo in home gli ultimi post:

1 var posts = ( from p in db.Posts

where p.IsPublished

orderby p.CreatedDate descending

select p ).Skip(0)

.Take(3)

.ToList<Post>();

Mostriamo in home gli ultimi post:

2

var posts = ( from p in db.Posts

where p.IsPublished

orderby p.CreatedDate descending

select p ).Skip(0)

.Take(3)

.ToList<Post>();

ViewBag.Posts = posts;

Mostriamo in home gli ultimi post:

var posts = ( from p in db.Posts

where p.IsPublished

orderby p.CreatedDate descending

select p ).Skip(0)

.Take(3)

.ToList<Post>();

ViewBag.Posts = posts;

3 @foreach (var item in (IList<Post>)ViewBag.Posts)

{

<h2>@item.Title</h2>

<h3>Pubblicato il @item.PublishedDate</h3>

<p>@item.Body</p>

<p class="tags">@item.Tags</p>

}

Il ViewBag è molto comodo, ma ci

costringe a eseguire sempre un cast

prima di utilizzarlo se la proprietà è un

oggetto complesso

@foreach (var item in (IList<Post>)ViewBag.Posts)

{

<h2>@item.Title</h2>

<h3>Pubblicato il @item.PublishedDate</h3>

<p>@item.Body</p>

<p class="tags">@item.Tags</p>

}

Strongly-typed views

Possiamo dire alla vista il

tipo del modello che gli

passiamo

Strongly-typed views

public ActionResult Index() {

var posts = …;

ViewBag.Posts = posts;

return View(posts);

}

Strongly-typed views

@using WebApp.Blog.Domain.Model;

@model IList<Post>

@foreach(var item in Model)

{

Blocco di codice:

@ {

ViewBag.Title = "Home Page";

}

Espressione con html encoding

<h2>@item.Title</h2>

Espressione senza encoding

<p>@Html.Raw(item.Title)</p>

Chiamata di un metodo

<p>@(DateTime.Now.ToLocalTime()))</p>

Controllo del flusso

@foreach (var item in Model)

{

<h2>@item.Title</h2>

<p>@item.Body</p>

<p class="tags">@item.Tags</p>

}

Mescolare codice e testo

@foreach (var item in Model)

{

<h2>@item.Title</h2>

<p>@item.Body</p>

<p class="tags">@item.Tags</p>

<text>Copyright - 2012</text>

}

Selezionando le parti comuni

tra le pagine del nostro sito

possiamo definire un layout

e delle sezioni da riutilizzare

Layout

<!DOCTYPE html>

<html>

<head><title>@ViewBag.Title</title></head>

<body>

<header>

<h1>My MVC Application</h1>

</header>

<section id="main">

@RenderBody()

</section>

<footer>@RenderSection("Footer")</footer>

</body>

</html>

Layout

<!DOCTYPE html>

<html>

<head><title>@ViewBag.Title</title></head>

<body>

<header>

<h1>My MVC Application</h1>

</header>

<section id="main">

@RenderBody()

</section>

<footer>@RenderSection("Footer")</footer>

</body>

</html>

Layout

<!DOCTYPE html>

<html>

<head><title>@ViewBag.Title</title></head>

<body>

<header>

<h1>My MVC Application</h1>

</header>

<section id="main">

@RenderBody()

</section>

<footer>@RenderSection("Footer")</footer>

</body>

</html>

Layout

Come faccio a fare in modo che la

vista utilizzi un determinato layout?

Layout

@{

ViewBag.Title = "Home Page";

Layout = "~/Views/Shared/_Layout.cshtml";

}

Ma lo devo fare per ogni vista?!

Layout

Ma lo devo fare per ogni vista?!

NO, basta utilizzare il ViewStart …

Layout

E’ un file che viene inserito nella

cartella principale e permette di far

applicare delle regole a tutte le

viste presenti in quella cartella e in

tutte le sue sottocartelle

_ViewStart

Se le informazioni da visualizzare

sono le stesse (o quasi) per molte

pagine, allora possiamo creare una

“vista parziale” che le contenga

PartialView

<footer>@Html.Partial("Footer")</footer>

PartialView

Nel layout o nella view

<p>Copyright © 2012</p>

In un file con nome Footer.cshtml (sotto la cartella ~/Shared )

Se non mi basta la vista parziale

posso ricorrere alle “child action”

RenderAction

RenderAction @{ Html.RenderAction("List", "Category"); }

All’interno

di una vista

1

RenderAction

2 public ActionResult List()

{

IList<Category> cat_s = new List<Category>();

using (var db = new BlogContext())

{

cat_s = (from c in db.Categories.Include("Posts")

select c).ToList<Category>();

}

return PartialView(categories);

}

Come action di

un controller

RenderAction

3 @using WebApp.Blog.Domain.Model;

@model ICollection<Category>

<h2>Categorie</h2>

<ul>

@foreach (var item in Model)

{

<li>

@item.Name

(@(item.Posts != null ? item.Posts.Count() : 0))

</li>

}

</ul>

Codice di markup

della partialview

Una pagina che visualizzi tutti i

post di una categoria

Una pagina che mostri i dati di un

post compresi i commenti

Paginare l’home page per

mostrare i post meno recenti

Come esercizio:

continua …

Slide 10: http://www.flickr.com/photos/jeffwerner/2677245039/in/photostream/

Slide 13: http://www.flickr.com/photos/philthomas/3345060816/in/photostream/

Credits Le immagini contenute in questa presentazione

hanno licenza Creative Commons

Thank You

MANUEL SCAPOLAN website: www.manuelscapolan.it twitter: manuelscapolan e-mail: info@manuelscapolan.it