In the previous post in this Contoso Karate MVC Series we re-factored our LogIn control widget into a PartialView. We did this for a few reasons.

  • Views want to be associated with only one model and we want to reserve that model for one that is more central to the particular page being displayed. (Specifying the Model for the view in the page _Template is generally a bad idea since that model will then be THE model assumed for every page that derives from that template. Partial views are one of the ways that we can solve this problem, a ViewModel is another.)
  • Partial views are very easily reusable.
  • If other considerations don’t preempt their use, Partial Views can make your actual View Markup easier to understand.

In this post I’ll build another Partial View. Please read the previous post to understand why we need partial views in the context of our fairly complex user interface design.

So, lets suppose that we have a requirement for an alert / notice box on our home page. It could contain special data, like for example a notice that classes are canceled due to bad weather.

It might look like this.

In this case our UI Widget is slightly more complex because we will need to retrieve data from a database to display from inside our partial view. We will store all the site notices in the database so that we have a historical record but we’ll only display the most recent one.

So, we’ll need a data table to store our notices. I like to keep the ASP.NET Services data (membership, etc) separate from my domain specific data so I created a new database named CKCMS for Contoso Karate Content Management System.

You probably know the drill. Right-Click in the solution, select Add -> New Item, choose the data items collection and select New SQL Server Database.

In Visual Studio, Switch from the Solution Explorer to the Database Explorer.

Expand the view on the database that was just created and right-click on the tables folder.

Add the fields as shown in the following table view.

When you save the table, name it “Notices”.

Note that the IsLive column will not be used in this demo. I’ve added it for future use. (We may want to be able to display more than one notice at a time in a future version of the application.)

Since we’ll need to access the data, I created an ADO.NET Entity Model.

Right-Click on the Models folder and choose add new item.

Select “Data” to see the data items collection and choose ADO.NET Entity Data Model and specify the name “CKSMSDBModel”  (Contoso Karate Content Management System Database Model.)

On the next screen select “Generate from Database” and click next.

Use the connection drop-down to choose the CKCMS database that we created earlier and set the name for the connection string to CKCMSEntities.

Select the Notices table and Click Next.



Click Finish !

A visual representation of the generated entity model will appear.

Now lets create the Partial View that will display the “notice” box on the home page. Since this partial view will only be used in the default Home view, we’ll create it in the Views/Home folder.

Right-Click -> Add -> View

Name your view _NoticeBoxPartial.cshtml

The code will be as follows:


@model ContosoKarateMVC.Models.Notice
   
<div class='style-post'>
    <div class='style-post-tl'></div>
    <div class='style-post-tr'></div>
    <div class='style-post-bl'></div>
    <div class='style-post-br'></div>
    <div class='style-post-tc'></div>
    <div class='style-post-bc'></div>
    <div class='style-post-cl'></div>
    <div class='style-post-cr'></div>
    <div class='style-post-cc'></div>
    <div class='style-post-body'>
        <div class='style-post-inner style-article'>
            <div class='style-postmetadataheader'>
                <h2 class='style-postheader'>
                    @Model.Title 
                </h2>
            </div>
            <br />
            <div class='style-postcontent'>
                    @Model.Message
            </div>
            <div class='cleared'></div>
        </div>
        <div class='cleared'></div>
    </div>
</div>

Take special note of line #1 where we specify that this View will recieve an object instance of type “ContosoKarateMVC.Models.Notice” which is defined in the code that was generated when we added the ADO.NET Entity Data Model.

Note also Lines #17 and #22 where we extract values from the “Notice” Object Instance that the view receives. These values are inserted into the html being emitted by the partial view.

There are still two tasks for us to code.

First we need to include the PartialView in our default Home View. When we positioned the LogOn partial view (previous post) we used the Razor method ” @{ Html.RenderPartial(“_LoginBoxPartial”); }”

In this case, however, we need to retrieve some data from the database before we can render the Notice PartialView so we’ll need to execute an action in our Home View.

At the top of Home\Index.cshtml, modify the code block as follows.


@{
    ViewBag.Title = 'Home Page';

    Html.RenderAction('NoticeBox', 'Home');                
}

Note that we have not referenced the Partial View yet. We are calling an action on the “Home” controller named “NoticeBox()” which we haven’t defined yet.

To define the action lets open the HomeController.cs file and update it to look like this.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ContosoKarateMVC.Models;

namespace ContosoKarateMVC.Controllers
{
    public class HomeController : Controller
    {
        CKCMSEntities db = new CKCMSEntities();

        public ActionResult Index()
        {
            ViewBag.Message = 'Welcome to ASP.NET MVC!';

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        [ChildActionOnly]
        public ActionResult NoticeBox() 
        {
            var n = db.Notices.OrderBy(notice => notice.DateTimeCreated)   
			                  .FirstOrDefault();

            return PartialView('_NoticeBoxPartial', n);             
        } 

     }
  }

There are a few code modifications from the default.

On line #6 we pull in our web site Models (using ContosoKarateMVC.Models;) We will manually code some models in the future but right now the models are the AccountModel which is generated from the default site template when we first created our web site and from the ADO.NET Entity Model that we generated above. The namespace “ContosoKarateMVC uses the project name by default.

We create an entities instance (wired up to our database) on line #12

On line #27 we declare the ActionResult method which we name NoticeBox (which as you will recall, we referenced in our Home/Index.cshtml page)

The [ChildActionOnly] attribute on line #26 just specifies that this action can not be directly invoked.

We access the database on line #29


var n = db.Notices.OrderBy(notice => notice.DateTimeCreated).FirstOrDefault(); 

This line queries the records in the notices table, sorted by the date field, and selects the most recent.

The resultant entity instance is stored in the variable “n”.

“n” is an object instance of type “ContosoKarateMVC.Models.Notice” which is exactly what our partial view is expecting, so, in line #31 we return our partial view ( _NoticeBoxPartial ) and pass to that partial view the ContosoKarateMVC.Models.Notice object instance “n”.

When the partial view is rendered it will now have a “notice” object from with it can extract and render the notice “Title” and “Message”.

I pre-populated a record in the Notices table with title “Become a Student”.

Running the application now results in what you see in the image at the top of this post.

That’s it !

You can download teh runnable source code [ HERE ]