Friday, May 11, 2012

Viewing and Creating Albums, part 1

Now, lets go deeper in the document structure and deal with albums. We'll start by revisiting the BandController class. The first thing I did was change the default Index action to the following...



        public ActionResult Index(string band_id)
        {
            var band = session.Load<Models.Band>(band_id);
            var albums = (from a in band.Albums
                         orderby a.Name
                         select a).ToList();
            ViewBag.Band = band;
            return View(albums);
        }



Note that this action requires a string. That got passed by the link in the /Band/Index view. The Load method loads the band with that ID into memory. I added a Boolean HasYear field to the Album class too. The /Album/Index view is strongly typed, as follows:



@model List<MvcRavenCDApp1.Models.Album>


@{
    ViewBag.Title = "Index";
}


<h2>Index</h2>
<h3>Here are the albums on file by @ViewBag.Band.Name</h3>
<p>Click on the album's name for a tracklist</p>
<table>
  <tr>
    <th>Name</th>
    <th>Year</th>
    <th>CD Number</th>
  </tr>
  @foreach (var album in Model)
  {
      <tr>
        <td>@Html.ActionLink(album.Name, "../Track/Index/" + (string)ViewBag.Band.Id + "/" + album.Id)</td>
        <td>@((album.HasYear) ? album.Year.ToString() : "(not on file)")</td>
        <td>@album.CDNumber.ToString()</td>
      </tr>
  }
</table>
<p>@Html.ActionLink("Add a CD by " + (string)ViewBag.Band.Name, "../Album/Add/" + (string)ViewBag.Band.Id)</p>


Notice the explicit casting. That's because the ActionLink method doesn't know what to do with ViewBag's members otherwise. Here is what that screen looks like so far:



In the next installment, I'll show you how to add CDs to the band document.



No comments:

Post a Comment