SlideShare a Scribd company logo
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

More Related Content

PDF
ASP.NET MVC3 - Tutti i compiti del Controller
PDF
Introduzione a node.js
PPT
Java lezione 16
PDF
jQuery - 1 | WebMaster & WebDesigner
PDF
Luca Masini: Introduzione a GWT 2.0
PDF
Javascript - 4 | WebMaster & WebDesigner
PDF
jQuery - 1 | WebMaster & WebDesigner
ODP
Rich Ajax Web Interfaces in Jquery
ASP.NET MVC3 - Tutti i compiti del Controller
Introduzione a node.js
Java lezione 16
jQuery - 1 | WebMaster & WebDesigner
Luca Masini: Introduzione a GWT 2.0
Javascript - 4 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesigner
Rich Ajax Web Interfaces in Jquery

Viewers also liked (7)

PPSX
Entity Framework 4.0 vs NHibernate
KEY
IDC CS4Real presentation
PDF
ASP.NET MVC Intro
PDF
C# e la Framework Class Library
PDF
PDF
Mobile first strategy, When, why ( and why Not )
PDF
Managed Extensibility Framework (MEF)
Entity Framework 4.0 vs NHibernate
IDC CS4Real presentation
ASP.NET MVC Intro
C# e la Framework Class Library
Mobile first strategy, When, why ( and why Not )
Managed Extensibility Framework (MEF)
Ad

Similar to ASP.NET MVC 3 - Presentare i dati nella View (20)

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

More from Manuel Scapolan (12)

PDF
TFS and Scrum - Lessons Learned
PDF
Scrum? E' come fare il bucato!
PDF
Domain Driven Design e CQRS
PDF
PDF
Knockout.js
PDF
ASP.NET MVC 3 - Trasportare i dati nel Model
PDF
JavaScript Object Oriented
PDF
HTML e CSS
PDF
Tutte le novità di ASP.NET MVC3
PDF
Dai delegati a LINQ con C#
PDF
AntiPatterns: i vizi del programmatore
PDF
OOP with C#
TFS and Scrum - Lessons Learned
Scrum? E' come fare il bucato!
Domain Driven Design e CQRS
Knockout.js
ASP.NET MVC 3 - Trasportare i dati nel Model
JavaScript Object Oriented
HTML e CSS
Tutte le novità di ASP.NET MVC3
Dai delegati a LINQ con C#
AntiPatterns: i vizi del programmatore
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