SlideShare ist ein Scribd-Unternehmen logo
1 von 51
Downloaden Sie, um offline zu lesen
Sviluppo applicazioni web e linguaggio HTML

                               LEZIONE 05




ASP.NET
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?
ViewBag
In una valigia,
ovviamente …
ViewBag
dynamic al quale
possiamo assegnare
proprietà arbitrarie
ViewBag.TotalPosts
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;
In realtà …




Il ViewBag permette di rendere dinamico
l’accesso ad un dizionario, il ViewData
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;
ViewData[“TotalComments”] = totalComments;
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:
    var posts = ( from p in db.Posts
                  where p.IsPublished
                  orderby p.CreatedDate descending
                  select p ).Skip(0)
                            .Take(3)
                            .ToList<Post>();
2   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>
}
Layout
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?

@{
     ViewBag.Title = "Home Page";
     Layout = "~/Views/Shared/_Layout.cshtml";
}
Layout
Ma lo devo fare per ogni vista?!
Layout
Ma lo devo fare per ogni vista?!

NO, basta utilizzare il ViewStart …
_ViewStart
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
PartialView
Se le informazioni da visualizzare
sono le stesse (o quasi) per molte
pagine, allora possiamo creare una
“vista parziale” che le contenga
PartialView
Nel layout o nella view
<footer>@Html.Partial("Footer")</footer>


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

<p>Copyright © 2012</p>
RenderAction
Se non mi basta la vista parziale
posso ricorrere alle “child action”
RenderAction
1   @{ Html.RenderAction("List", "Category"); }



                               All’interno
                               di una vista
RenderAction
                                       Come action di
                                       un controller


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);
    }
Codice di markup
RenderAction                          della partialview


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>
Come esercizio:
 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
continua …
Credits
Le immagini contenute in questa presentazione
hanno licenza Creative Commons


Slide 10: http://www.flickr.com/photos/jeffwerner/2677245039/in/photostream/
Slide 13: http://www.flickr.com/photos/philthomas/3345060816/in/photostream/
Thank You   MANUEL SCAPOLAN
            website: www.manuelscapolan.it
            twitter: manuelscapolan
            e-mail: info@manuelscapolan.it

Weitere ähnliche Inhalte

Andere mochten auch

Entity Framework 4.0 vs NHibernate
Entity Framework 4.0 vs NHibernateEntity Framework 4.0 vs NHibernate
Entity Framework 4.0 vs NHibernateManuel Scapolan
 
IDC CS4Real presentation
IDC CS4Real presentationIDC CS4Real presentation
IDC CS4Real presentationShai Wolkomir
 
C# e la Framework Class Library
C# e la Framework Class LibraryC# e la Framework Class Library
C# e la Framework Class LibraryManuel Scapolan
 
Mobile first strategy, When, why ( and why Not )
Mobile first strategy, When, why ( and why Not ) Mobile first strategy, When, why ( and why Not )
Mobile first strategy, When, why ( and why Not ) Shai Wolkomir
 
Managed Extensibility Framework (MEF)
Managed Extensibility Framework (MEF)Managed Extensibility Framework (MEF)
Managed Extensibility Framework (MEF)Manuel Scapolan
 

Andere mochten auch (7)

Entity Framework 4.0 vs NHibernate
Entity Framework 4.0 vs NHibernateEntity Framework 4.0 vs NHibernate
Entity Framework 4.0 vs NHibernate
 
IDC CS4Real presentation
IDC CS4Real presentationIDC CS4Real presentation
IDC CS4Real presentation
 
ASP.NET MVC Intro
ASP.NET MVC IntroASP.NET MVC Intro
ASP.NET MVC Intro
 
C# e la Framework Class Library
C# e la Framework Class LibraryC# e la Framework Class Library
C# e la Framework Class Library
 
ASP.NET
ASP.NETASP.NET
ASP.NET
 
Mobile first strategy, When, why ( and why Not )
Mobile first strategy, When, why ( and why Not ) Mobile first strategy, When, why ( and why Not )
Mobile first strategy, When, why ( and why Not )
 
Managed Extensibility Framework (MEF)
Managed Extensibility Framework (MEF)Managed Extensibility Framework (MEF)
Managed Extensibility Framework (MEF)
 

Ähnlich wie ASP.NET MVC 3 - Presentare i dati nella View

Javascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesignerJavascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesignerMatteo Magni
 
Asp.Net MVC 3 - Il Model View Controller secondo Microsoft
Asp.Net MVC 3 - Il Model View Controller secondo MicrosoftAsp.Net MVC 3 - Il Model View Controller secondo Microsoft
Asp.Net MVC 3 - Il Model View Controller secondo MicrosoftStefano Benedetti
 
Qt Lezione4 Parte2: creare un custom widget plugin per Qt Designer
Qt Lezione4 Parte2: creare un custom widget plugin per Qt DesignerQt Lezione4 Parte2: creare un custom widget plugin per Qt Designer
Qt Lezione4 Parte2: creare un custom widget plugin per Qt DesignerPaolo Sereno
 
L'Arte del Templating: Typoscript, Fluid e Grid Elements
L'Arte del Templating: Typoscript, Fluid e Grid ElementsL'Arte del Templating: Typoscript, Fluid e Grid Elements
L'Arte del Templating: Typoscript, Fluid e Grid ElementsElena Bartolotti
 
04 Tapestry5 In Action Pratica
04   Tapestry5 In Action   Pratica04   Tapestry5 In Action   Pratica
04 Tapestry5 In Action Praticabobpuley
 
Session 02 - schema design e architettura
Session 02 - schema design e architetturaSession 02 - schema design e architettura
Session 02 - schema design e architetturaMongoDB
 
ZoeFX: un framework MVC per JavaFX
ZoeFX: un framework MVC per JavaFXZoeFX: un framework MVC per JavaFX
ZoeFX: un framework MVC per JavaFXTiziano Lattisi
 
Drupal diventa un CMF e WordPress che fa? Slide WordCamp Milano 2019
Drupal diventa un CMF e WordPress che fa? Slide WordCamp Milano 2019Drupal diventa un CMF e WordPress che fa? Slide WordCamp Milano 2019
Drupal diventa un CMF e WordPress che fa? Slide WordCamp Milano 2019Matteo Enna
 
Bootstrap 3.0 - Introduzione
Bootstrap 3.0 - IntroduzioneBootstrap 3.0 - Introduzione
Bootstrap 3.0 - IntroduzioneMatteo Madeddu
 
Inserire ultimi articoli su blogger
Inserire ultimi articoli su bloggerInserire ultimi articoli su blogger
Inserire ultimi articoli su bloggerStefano Vinci
 
How To React - Gestione Stato Applicativo
How To React - Gestione Stato ApplicativoHow To React - Gestione Stato Applicativo
How To React - Gestione Stato ApplicativoAldoNoschese
 
Dal RenderFragment ai Generics, tips for Blazor developers
Dal RenderFragment ai Generics, tips for Blazor developersDal RenderFragment ai Generics, tips for Blazor developers
Dal RenderFragment ai Generics, tips for Blazor developersAndrea Dottor
 
Write less do more...with jQuery
Write less do more...with jQueryWrite less do more...with jQuery
Write less do more...with jQueryXeDotNet
 
What's New in ASP.NET 4.5 and Visual Studio 2012
What's New in ASP.NET 4.5 and Visual Studio 2012What's New in ASP.NET 4.5 and Visual Studio 2012
What's New in ASP.NET 4.5 and Visual Studio 2012Andrea Dottor
 

Ähnlich wie ASP.NET MVC 3 - Presentare i dati nella View (20)

Javascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesignerJavascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesigner
 
Asp.Net MVC 3 - Il Model View Controller secondo Microsoft
Asp.Net MVC 3 - Il Model View Controller secondo MicrosoftAsp.Net MVC 3 - Il Model View Controller secondo Microsoft
Asp.Net MVC 3 - Il Model View Controller secondo Microsoft
 
Codemotion workshop
Codemotion workshopCodemotion workshop
Codemotion workshop
 
react-it.pdf
react-it.pdfreact-it.pdf
react-it.pdf
 
Qt Lezione4 Parte2: creare un custom widget plugin per Qt Designer
Qt Lezione4 Parte2: creare un custom widget plugin per Qt DesignerQt Lezione4 Parte2: creare un custom widget plugin per Qt Designer
Qt Lezione4 Parte2: creare un custom widget plugin per Qt Designer
 
L'Arte del Templating: Typoscript, Fluid e Grid Elements
L'Arte del Templating: Typoscript, Fluid e Grid ElementsL'Arte del Templating: Typoscript, Fluid e Grid Elements
L'Arte del Templating: Typoscript, Fluid e Grid Elements
 
04 Tapestry5 In Action Pratica
04   Tapestry5 In Action   Pratica04   Tapestry5 In Action   Pratica
04 Tapestry5 In Action Pratica
 
Corso angular js componenti
Corso angular js componentiCorso angular js componenti
Corso angular js componenti
 
Many Designs Elements
Many Designs ElementsMany Designs Elements
Many Designs Elements
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Session 02 - schema design e architettura
Session 02 - schema design e architetturaSession 02 - schema design e architettura
Session 02 - schema design e architettura
 
ZoeFX: un framework MVC per JavaFX
ZoeFX: un framework MVC per JavaFXZoeFX: un framework MVC per JavaFX
ZoeFX: un framework MVC per JavaFX
 
Laravel Framework PHP
Laravel Framework PHPLaravel Framework PHP
Laravel Framework PHP
 
Drupal diventa un CMF e WordPress che fa? Slide WordCamp Milano 2019
Drupal diventa un CMF e WordPress che fa? Slide WordCamp Milano 2019Drupal diventa un CMF e WordPress che fa? Slide WordCamp Milano 2019
Drupal diventa un CMF e WordPress che fa? Slide WordCamp Milano 2019
 
Bootstrap 3.0 - Introduzione
Bootstrap 3.0 - IntroduzioneBootstrap 3.0 - Introduzione
Bootstrap 3.0 - Introduzione
 
Inserire ultimi articoli su blogger
Inserire ultimi articoli su bloggerInserire ultimi articoli su blogger
Inserire ultimi articoli su blogger
 
How To React - Gestione Stato Applicativo
How To React - Gestione Stato ApplicativoHow To React - Gestione Stato Applicativo
How To React - Gestione Stato Applicativo
 
Dal RenderFragment ai Generics, tips for Blazor developers
Dal RenderFragment ai Generics, tips for Blazor developersDal RenderFragment ai Generics, tips for Blazor developers
Dal RenderFragment ai Generics, tips for Blazor developers
 
Write less do more...with jQuery
Write less do more...with jQueryWrite less do more...with jQuery
Write less do more...with jQuery
 
What's New in ASP.NET 4.5 and Visual Studio 2012
What's New in ASP.NET 4.5 and Visual Studio 2012What's New in ASP.NET 4.5 and Visual Studio 2012
What's New in ASP.NET 4.5 and Visual Studio 2012
 

Mehr von Manuel Scapolan

TFS and Scrum - Lessons Learned
TFS and Scrum - Lessons LearnedTFS and Scrum - Lessons Learned
TFS and Scrum - Lessons LearnedManuel Scapolan
 
Scrum? E' come fare il bucato!
Scrum? E' come fare il bucato!Scrum? E' come fare il bucato!
Scrum? E' come fare il bucato!Manuel Scapolan
 
Domain Driven Design e CQRS
Domain Driven Design e CQRSDomain Driven Design e CQRS
Domain Driven Design e CQRSManuel Scapolan
 
ASP.NET MVC 3 - Trasportare i dati nel Model
ASP.NET MVC 3 - Trasportare i dati nel ModelASP.NET MVC 3 - Trasportare i dati nel Model
ASP.NET MVC 3 - Trasportare i dati nel ModelManuel Scapolan
 
JavaScript Object Oriented
JavaScript Object OrientedJavaScript Object Oriented
JavaScript Object OrientedManuel Scapolan
 
Tutte le novità di ASP.NET MVC3
Tutte le novità di ASP.NET MVC3Tutte le novità di ASP.NET MVC3
Tutte le novità di ASP.NET MVC3Manuel Scapolan
 
Dai delegati a LINQ con C#
Dai delegati a LINQ con C#Dai delegati a LINQ con C#
Dai delegati a LINQ con C#Manuel Scapolan
 
AntiPatterns: i vizi del programmatore
AntiPatterns: i vizi del programmatoreAntiPatterns: i vizi del programmatore
AntiPatterns: i vizi del programmatoreManuel Scapolan
 

Mehr von Manuel Scapolan (12)

TFS and Scrum - Lessons Learned
TFS and Scrum - Lessons LearnedTFS and Scrum - Lessons Learned
TFS and Scrum - Lessons Learned
 
Scrum? E' come fare il bucato!
Scrum? E' come fare il bucato!Scrum? E' come fare il bucato!
Scrum? E' come fare il bucato!
 
Domain Driven Design e CQRS
Domain Driven Design e CQRSDomain Driven Design e CQRS
Domain Driven Design e CQRS
 
NOSQL
NOSQLNOSQL
NOSQL
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
ASP.NET MVC 3 - Trasportare i dati nel Model
ASP.NET MVC 3 - Trasportare i dati nel ModelASP.NET MVC 3 - Trasportare i dati nel Model
ASP.NET MVC 3 - Trasportare i dati nel Model
 
JavaScript Object Oriented
JavaScript Object OrientedJavaScript Object Oriented
JavaScript Object Oriented
 
HTML e CSS
HTML e CSSHTML e CSS
HTML e CSS
 
Tutte le novità di ASP.NET MVC3
Tutte le novità di ASP.NET MVC3Tutte le novità di ASP.NET MVC3
Tutte le novità di ASP.NET MVC3
 
Dai delegati a LINQ con C#
Dai delegati a LINQ con C#Dai delegati a LINQ con C#
Dai delegati a LINQ con C#
 
AntiPatterns: i vizi del programmatore
AntiPatterns: i vizi del programmatoreAntiPatterns: i vizi del programmatore
AntiPatterns: i vizi del programmatore
 
OOP with C#
OOP with C#OOP with C#
OOP with C#
 

ASP.NET MVC 3 - Presentare i dati nella View

  • 1. Sviluppo applicazioni web e linguaggio HTML LEZIONE 05 ASP.NET Model View Controller
  • 3. Con le View mostriamo i dati all’utente
  • 6. Quelli del model … Visualizziamo in homepage il numero totale di post e commenti utilizzando il DbContext
  • 7. 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(); }
  • 8. … e nella vista i dati come li trasportiamo?
  • 10. ViewBag dynamic al quale possiamo assegnare proprietà arbitrarie
  • 11. ViewBag.TotalPosts dynamic al quale possiamo assegnare proprietà arbitrarie
  • 12. 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;
  • 13. In realtà … Il ViewBag permette di rendere dinamico l’accesso ad un dizionario, il ViewData
  • 14. 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; ViewData[“TotalComments”] = totalComments;
  • 15. ma vediamo come nella vista i dati del model si mescolano al codice html …
  • 16. ma vediamo come nella vista i dati del model si mescolano al codice html …
  • 17. Questa sintassi in esecuzione viene interpretata da un View Engine
  • 18. 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.
  • 19. 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
  • 20. Mostriamo in home gli ultimi post:
  • 21. 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>();
  • 22. 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>(); 2 ViewBag.Posts = posts;
  • 23. 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> }
  • 24. 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> }
  • 25. Strongly-typed views Possiamo dire alla vista il tipo del modello che gli passiamo
  • 26. Strongly-typed views public ActionResult Index() { … var posts = …; ViewBag.Posts = posts; return View(posts); }
  • 27. Strongly-typed views @using WebApp.Blog.Domain.Model; @model IList<Post> @foreach(var item in Model) { …
  • 28. Blocco di codice: @{ ViewBag.Title = "Home Page"; }
  • 29. Espressione con html encoding <h2>@item.Title</h2>
  • 31. Chiamata di un metodo <p>@(DateTime.Now.ToLocalTime()))</p>
  • 32. Controllo del flusso @foreach (var item in Model) { <h2>@item.Title</h2> <p>@item.Body</p> <p class="tags">@item.Tags</p> }
  • 33. 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> }
  • 34. Layout Selezionando le parti comuni tra le pagine del nostro sito possiamo definire un layout e delle sezioni da riutilizzare
  • 35. 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>
  • 36. 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>
  • 37. 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>
  • 38. Layout Come faccio a fare in modo che la vista utilizzi un determinato layout? @{ ViewBag.Title = "Home Page"; Layout = "~/Views/Shared/_Layout.cshtml"; }
  • 39. Layout Ma lo devo fare per ogni vista?!
  • 40. Layout Ma lo devo fare per ogni vista?! NO, basta utilizzare il ViewStart …
  • 41. _ViewStart 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
  • 42. PartialView Se le informazioni da visualizzare sono le stesse (o quasi) per molte pagine, allora possiamo creare una “vista parziale” che le contenga
  • 43. PartialView Nel layout o nella view <footer>@Html.Partial("Footer")</footer> In un file con nome Footer.cshtml (sotto la cartella ~/Shared ) <p>Copyright © 2012</p>
  • 44. RenderAction Se non mi basta la vista parziale posso ricorrere alle “child action”
  • 45. RenderAction 1 @{ Html.RenderAction("List", "Category"); } All’interno di una vista
  • 46. RenderAction Come action di un controller 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); }
  • 47. Codice di markup RenderAction della partialview 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>
  • 48. Come esercizio:  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
  • 50. Credits Le immagini contenute in questa presentazione hanno licenza Creative Commons Slide 10: http://www.flickr.com/photos/jeffwerner/2677245039/in/photostream/ Slide 13: http://www.flickr.com/photos/philthomas/3345060816/in/photostream/
  • 51. Thank You MANUEL SCAPOLAN website: www.manuelscapolan.it twitter: manuelscapolan e-mail: info@manuelscapolan.it