Friday, April 13, 2012

Viewing And Creating Bands

I'm back. Now for my first controllers and views...
I created a controller called HomeController and filled in the "Index" action as follows:


        public ActionResult Index()
        {
            var session = MvcApplication.documentStore.OpenSession();


            var bands = (from b in session.Query<Models.Band>()
                         orderby b.Name
                         select b).ToList();


            return View(bands);
        }


The "session" variable should look familiar. The LINQ sorts all the Band objects (documents) by band name. You would normally use the Query method to search multiple documents when using Raven. 

Here is the Razor code for that action's view:


@model List<MvcRavenCDApp1.Models.Band>


@{
    ViewBag.Title = "Index";
}


<h2>Index</h2>
<p>Click on a band name to see that band's CDs on file...</p>
<ul>
@foreach (var band in Model)
{
    <li><a href="../Band/Index/@band.Id">@band.Name (@(band.HasDescription ? band.Description : "no descr.")) </a></li>
}
</ul>


<p>@Html.ActionLink("Add a band", "../Band/Add")</p>


Here's what I saw when I first ran the program...


As you can see, there was no data, as I hadn't added any bands. Now you can see why I use booleans like "HasDescription". In order to add bands, I had to create an input form. The first step was to create BandController. Then, I created the constructor and "Add" action as follows:

        private IDocumentSession session;

        public BandController()
        {
            session = MvcApplication.documentStore.OpenSession();
        }
...

        [HttpGet]
        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public RedirectResult Add(Models.Band band)
        {
            band.Albums = new List<Models.Album>();
            if (String.IsNullOrWhiteSpace(band.Description))
            {
                band.HasDescription = false;
            }
            else
            {
                band.HasDescription = true;
            }
            session.Store(band);
            session.SaveChanges();
            return Redirect("/Home/Index");
        }

That view's code was the following:

@model MvcRavenCDApp1.Models.Band

@{
    ViewBag.Title = "Add";
}

<h2>Add A Band</h2>
@using (Html.BeginForm())
{
    <p>Band/Artist Name: @Html.TextBoxFor(x => x.Name, new { @required = "true" })</p>
    <p>Genre/Description (optional): @Html.TextBoxFor(x => x.Description)</p>
    <p><input type="submit" name="Submit" value="Add Band" /></p>
}



Note that my code makes use of the HTML 5 "required" attribute. Once I added a couple bands, the home page looked like:


A Band JSON document looked like:

If you look back, you can see that my code works around the band description being optional.  You'll notice that the value of the "Albums" key is an empty array. We will be entering albums in the next post. 





No comments:

Post a Comment