Home > BTI420 ASP.NET dev, Windows > Designing an ASP.NET MVC web app (version 1)

Designing an ASP.NET MVC web app (version 1)

January 28, 2013 Leave a comment Go to comments

This document builds on the content of the previous documents, and enables the new ASP.NET MVC programmer create a substantial web app that has a data model.

This document was most recently updated in January 2013.

The intended audience is students in Seneca College’s Software Development degree program.

This is the fifth in a series of five posts that enable students to get started with ASP.NET MVC web development. The five posts are:

  1. Get ready to create ASP.NET web apps
  2. Creating your first simple ASP.NET MVC web app
  3. Data persistence choices for ASP.NET MVC web apps
  4. Adding HTML Forms to ASP.NET MVC web apps
  5. Designing an ASP.NET MVC web app (version 1)

.

Introduction and context

In the previous posts/documents in the series, you learned the important getting-started topics for ASP.NET MVC web app development.

In this post/document, you will learn how to design an app to use a data model.

Download and study the “App design” programming code example. It expands upon the first “…Simple” example, by starting with a three-page web app (home/Index, About, Contact).

We will create an app that has the following design. To the existing controller(s) and view(s), we will add the following:

  • a model class,
  • a class that creates/initializes data for the app, and
  • a manager/repository class to centralize and manage access to the data.

.

System Design Guidance simplified

.

(Note: Some of the following was copy-pasted from a post that is, or will be deprecated. It still needs some editing.)

.

Creating and using data

Now it’s time to get data involved. This is the “model” part of the Model-View-Controller concept.

On the “Contact” page, you will add some info about how to contact you by phone (text message) and email. This can be done with HTML markup (go ahead and do that).

On the “About” page, you will add some info about yourself, including a list of courses that you’re in this semester. First, add the info about yourself, which will bea short paragraph, and add a photo. Store the photo in a new folder named “images”, located in the Content folder.

You could add the list of courses with markup (ul and li elements). However, let’s make it more interesting. We’ll create the list as data, in the controller, and pass it to the view. Then in the view, we’ll render the data in a table.

But first…

Classes that describe the data model

In this section, we will learn something about “data” in a C# app.

As you would expect in an object oriented programming environment, data are objects. Object types can be simple, holding a single data value; for example, intdoublestring, or DateTime.

In contrast, object types can be complex. Let’s create a “Subject” class. It will include “properties” – named data values – for data like subject code, professor name, and so on.

Where do you create a model class? For the next couple of weeks, create the class in the app’s Models folder. Right-click Models (or press Alt+Shift+C), and add a class; its name will be “Subject”.

A source code file, called Subject.cs, gets created, and inside, you will see the class definition; notice:

  • using directives, which bring a namespace’s types into scope
  • namespace declaration, which helps the programmer define and organize code elements that are somehow related (notice that by convention, its name is in the format <projectName>.<folderName>)
  • class declaration, which defines a scope for data and behaviours

What code can you put in a class?

  • Classes have “members” that represent their data and behaviour; common ones include:
  • Fields – often used for non-public internal use
  • Properties – typically used for publicly-accessible fields
  • Methods – for actions and behaviours; can have a mix of public and non-public methods
  • Constructors – method(s) used to initialize an object; called when an object is created

A class can inherit from another class (like other object oriented programming environments). C# offers single inheritance from a class (and multiple inheritance from interfaces; more about an “interface” later in the course). If the programmer does not declare the “inherits from” class, then by default, the class inherits from Object.

Subject class members

So, back to our Subject class… we need the following members:

  • Property – Id – int – a unique identifier for a subject
  • Property – DateCreated – DateTime – the current date and time the object was (will be) created
  • Property – Semester – string – for example, “Winter 2013”
  • Property – Code – string – for example, “BTI420”
  • Property – Name – string – for example, “Web Programming on Windows Servers”
  • Property – Professor – string – for example, “McIntyre, Peter”

Add these members to the class.

Properties can be added with a Visual Studio “snippet”. Type “prop” and press the Tab key twice. The code editor will insert a snippet, with highlighted fields that you can navigate between with Tab and Shift+Tab. On a field, simply type to replace its initial placeholder value. (As soon as you add a “newline”, i.e. press Enter at the end of the line of code, you lose the ability to navigate to that field.)

Also during the lecture, watch the professor demonstrate some features of the code editor.

Constructor

Think about the following simple scenario: Assume that you wish to create a Subject object somewhere in a controller. Do you want to make the programmer specify the DateCreated and Semester values? Both could be automatically configured when the new Subject object gets created – how?

Write a constructor:

  • Place the code for the constructor at the top of the class
  • Its syntax is simply the string “public className()”, with a { } code block
  • In the code block, DateCreated can be set with the value DateTime.Now
  • Semester can be set with the string “Winter 2013”

Convention tells us to use “this.” to prefix – also known as qualify – a member name (e.g. “this.Semester…”). The “this” keyword refers to the current instance of the class.

Creating an instance of this class (a Subject object) 

At this point, you have written a Subject class. In the Home controller, let’s create an instance of the subject class.

Remember the namespace declaration discussion above? We have to pay attention to this, because the Home controller does not yet know about our Subject class. To fix this, add another using directive (e.g. using project1.Models;) near the top of the source code file.

At the top of the Home controller class code (and before the existing methods), add a field to declare a single Subject. Like other C-based languages, the statement format is:
Type name = initialValue;

InitialValue is optional. For this example, leave off the initialValue – we’ll set the initial value in a constructor.

Next, add a constructor for the Home controller. Its code will create an instance of the Subject class:
private subject = new Subject();

We will then configure the public data members – the properties – of this new Subject object using a simple right-to-left assignment (except for the DateCreated and Semester properties, because they get created by the Subject class constructor). Properties are referenced / dereferenced using the dot symbol ( . ), like you would in a C struct.

Also, watch the professor demonstrate some features of the code editor.

Display data from the new Subject object 

Let’s display this new data. In the Index method, comment out the existing return View(); code. Then, use the return Content(); method again. The string argument can be a property of the subject object, e.g. subject.Name.

How can you create a string with the values of multiple fields? String concatenation. The ideal way to do this is to use the string.Format() method. It uses printf-style substitution syntax, using curly braces for the arguments. For example:

return Content(string.Format(“{0}<br />{1}”, subject.Name, subject.DateCreated.ToLongTimeString()));

(Why the <br /> instead of a \n newline character? Uh, what is the target of the output? A web browser!)

.

Model

You have just created and displayed a single Subject object. Let’s make this more interesting, by working with a collection of Subject objects.

In the .NET Framework, there are a number of kinds of collections. The most common kinds of collections are:

  • Generic list
  • Array
  • Dictionary

.

The first .NET Framework collection that you will learn about is the generic list, List<T>.

Generic classes and methods enable the programmer to design a class or method in a general or generic manner. Then, when using the class or method, the programmer can provide a specific type as a parameter. This approach promotes reusability, type safety, and efficiency.

You will know that a .NET Framework class or method uses generics when you see a type parameter T (upper-case letter “T”). That will tell you that you must provide a specific type name (e.g. string, int, or even “Subject” from above).

In HomeController, replace the statement that creates a single Subject object with the following statement, which creates a generic collection of Subject objects:
private List<Subject> subjects;

Next, in the HomeController constructor, replace the instantiation code with the following:
subjects = new List<Subject>();

At this point, you have declared and instantiated a “subjects” collection. To add Subject objects:

  1. Declare and instantiate a new Subject object
  2. Configure its properties
  3. Add the new Subject object, using the generic list’s “Add” method

.

Continue by adding two or more Subject objects, so that you have data to work with and display.

Display the Subject objects

In the HomeController Index method, we’ll write some code to display the Subject objects. Here’s our strategy:

  1. Declare a string that will accumulate the Subject Name string property
  2. Enumerate through the collection of Subject objects, extracting the Subject Name property, and adding it (in a properly-formatted manner) to the string
  3. Return the string accumulation with the Content method

Here’s the code:

string content = “”;
foreach (var s in subjects)
{
content += string.Format(“{0}<br />”, s.Name);
}
return Content(content);

Use the “foreach” snippet to create the foreach code block. Test your work (Ctrl+F5).

.

Strongly typed view

One of the fundamental features of the ASP.NET MVC framework is the ability to pass model data to a view, for rendering in a browser. This feature is known as strongly-typed views.

In HomeController, remove (or comment out, by selecting, then Ctrl+K, Ctrl+C) the code in the Index method that displayed the Subject collection. The Index method should simply return View();.

We need the Subject collection in the About view. Therefore, edit the About method so that it specifies the subjects collection as the argument:
return View(subjects);

Now, show the About view source code (About.cshtml).

Using the same reasoning as above (where the HomeController class didn’t know about the definition of the Subject class until we added a using directive), we must add a using directive to the view source code. Remember, a view contains markup and code expressions. We are adding a code expression, so we must prefix it with an “at sign” ( @ ).

Next, we must add a statement that declares (to the view) the data model’s type:
@model List<Subject>

This statement strongly types the model for the view, and enables you to use IntelliSense.

How do we suitably display the Subject object collection? As a web page designer, you could use a simple list, or you could use a table. In this example, we’ll use a simple unordered list.

As you know (duh), an unordered list nests li elements inside a ul element. Therefore, we need to write markup and code expressions inside the <ul> and </ul> tags that will produce li elements.

We use the foreach statement again. The simplest code would be:

<ul>
@foreach (var item in Model)
{
<li>@item.Name</li>
}
</ul>

.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: