MarkAFarrugia

Freelance Web Development in Malta

By

Create a simple ASP.NET MVC View to display data

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta which is a small island in the Mediterranean. So now let me start this blog post :) .

In this blog I will give an introduction on how to display data in an ASP.NET page. In particular I will be displaying products information in an ASP.NET MVC view. This information will be returned from an SQL Express database using LINQ To Entities. I will be explaining LINQ To Entities in a future blog but since what I will be covering is very easy I am sure you will not find any problems to follow this tutorial.

The outcome for this blog is thus

  1. To list records back from a database
The prerequisites to follow this blog are
  1. Installed SQL Server Express database. You can install it from here.
  2. Have a Products table as will be shown soon
  3. Know how to create a LINQ To Entities model which will help us in retrieving and updating records
 The Products table which we will be using in this blog should have these fields defined
  1. ProductId (uniqueidentifier)
  2. ProductName (varchar(50))
  3. ProductDesciption (varchar(50))
  4. ProductCategory (smallint)

Please note that ProductCategory will be related to another table Categories but for now I will not take this relationship into consideration

In the ASP.NET MVC Models folder (Figure 1) I will include the LINQ To Entities model. This LINQ To Entities model has only one single entity which is the Product entity which maps to the Products table. I will also place the classes which interact with the LINQ To Entities model which modify and retrieve data inside this folder. You will thus note that in this folder I will place anything which relates to the business layer.

Figure 1 - LINQ To Entities

Figure 1 – LINQ To Entities

Please note that normally I do not place the LINQ To Entities model and business logic inside the Models folder. Rather I normally create separate class libraries which provide the business logic. However, for now, I will be including everything in a single project.

The LINQ To Entities code which returns our all our products is shown underneath.

public IQueryable Product GetProducts()
{
Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
return entities.Products;
}

This code is basically some simple LINQ To Entities code which returns all our existing products.

Our first step is to create our Products controller which will be responsible in calling anything related to the Products (modifying and retrieving data) and then displaying it back to our views. If you are still unsure how to create controllers and views please refer to this blog post.

Add a new controller called ProductsController shown in Figure 2. Thus the user will be able to access our controller methods using our website url /Products. Our Index method will be responsible to get all the available products and return it back to the view.

Figure 2 - Products Controller

Figure 2 – Products Controller

Go into the Index method of our Products controller, click the right mouse button and click on Add View.

Now this is the fun part :) . Remember that our Index controller method will return a list of products from the LINQ To Entities model. Select Create a Strongly Typed View and select the Product class which is our LINQ To Entities model class. In the ScaffoldTemplate select List, as shown in Figure 3. Click on OK and your first ASP.NET MVC view which lists data is ready.

Figure 4 - Add View and Scaffold

Figure 3 – Add View and Scaffold

Now go back to your Index controller. To pass the Products list back to your view you need to modify your Index controller as shown below.

public ActionResult Index()
{
 Models.DBProducts db = new Models.DBProducts();
 return View(db.GetProducts());
}

Basically in the above code we are calling GetProducts which basically returns all our products.

If you now return your application and type /Products/Index in your URL you will view all your products as shown in Figure 5.

Products List

Figure 5 – Products List

 Can you see how easy it is to display data in a view from a controller? I’m sure that from now on you will be using this to display data :) .

In my next blog post I will going into detail on the HTML markup which is generated in the View we have created in this blog post.

By

Creating our first ASP.NET MVC View

In this blog post I will be creating our first simple ASP.NET MVC View which will just display a Hello World message :) . At the end of this blog you should be able to

  1. Start understanding how ASP.NET URL rewriting works
  2. Understand how to pass messages between a Controller and a View
  3. Understand how Controllers should be named
  4. Understand the mapping between Controller and their respective Views
  5. Understand where Views should be stored

To create our first View we will first be creating a Controller method inside the HomeController. Before I create our first View it is good to understand how ASP.NET controllers link to Views by giving several examples.

The first thing to understand is that all Controller names need to end with the Controller name. For example in the sample MVC application there are 2 controllers which are the HomeController and AccountController, as shown in Figure 1. In these controllers there are several methods which link to ASP.NET MVC Views. For example, in the HomeController there are 3 controller methods which are Index, About and Contact as shown in Figure 2.

Figure 1 - Home and Account Controller

Figure 1 – Home and Account Controller

Figure 2 - HomeController Methods

Figure 2 – HomeController Methods

How are these Controller methods called? I will be giving several examples underneath of different URLs the user can type in order to call these Controller methods

  1. http://localhost/Home/Index – The Index Controller method inside the HomeController is called.
  2. http://localhost/Home – The Index Controller method inside the HomeController is called
  3. http://localhost/Home/About -  The About Controller method inside the HomeController is called.
  4. http://localhost/Home/Contact -  The Contact Controller method inside the HomeController is called.

First of all if you take a look at the above URLs you will immediately realize that the URLs to access ASP.NET MVC pages are totally different from calling ASP.NET pages. The above URLs are much better for Search Engine Optimization (SEO), and sometimes these type of URLs are called slugs.

Taking the example URL shown underneath you will note that the first part is the Controller name while the second part is the Controller method name. So in the example shown Home represents the Controller name (in fact there is a Controller named HomeController), while Index is the Controller method name (in fact there is a method called Index in the Home Controller. (Figure 3) (Figure 4)

Figure 3 - Naming structure inside controllers

Figure 3 – Naming structure inside controllers

Figure 5 - URL Structure

Figure 5 – URL Structure

Let’s now create our ASP.NET MVC 4 view. Create a controller method called Test inside the HomeController, as shown in Figure 5 and type the following code return View(); This code basically returns the matching View with this Controller

Figure 5 - Test method

Figure 5 – Test method

Let’s run our application and let’s try to access our Controller method by typing http://localhost/Home/Test. You will see that an exception as shown in Figure 6 will be returned. The reason for this exception is that ASP.NET MVC will try to search for the relevant ASP.NET MVC view which relates to the Controller method. This View which should be named Test.cshtml should be stored inside the VIEWS-HOME folder. If this is not found then ASP.NET MVC will show the exception shown in Figure 6. ASP.NET MVC will try to find this page in several other locations and after failing to find any matching pages an exception will be thrown.

Figure 6 - Exception when View not found

Figure 6 – Exception when View not found

So where should ASP.NET views should be stored? All ASP.NET MVC views are stored inside the VIEWS folder. The naming structure which ASP.NET MVC adopts is that the folder relates to the Controller name, while the page will be named according to the method name.

So taking into account the example shown in Figure 5, a page named Test.cshtml should be created inside the Home folder. In fact, as shown in Figure 7, you will note that there are 3 pages which are related to the 3 methods which have been automatically created by our sample application. These views are named Home.cshtml, About.cshtml and Contact.cshtml.

Figure 7 - Sample Views

Figure 7 – Sample Views

Let’s go back to our example. If we wish to create a new View which will serve as our Test page we should go inside the Test controller method, click the right mouse button and then click on ADD VIEW. Figure 8 shows how this should be done.

Figure 8 - Add View

Figure 8 – Add View

You will then have to select several options. For now we will not go into detail into what this page provides. You only have to make sure that you select the MasterPage which in our sample application is called _Layout.cshtml and is found under the Shared folder, as shown in Figure 9. A page will be created. Now if you type in the URL http://localhost/Home/Test you will see that the page correctly opens as shown in Figure 10.

Figure 9 - Add View options

Figure 9 – Add View options

Figure 10 - View correctly loads

Figure 10 – View correctly loads

Now let’s try to send a message back to our view. To do this we can use what so called the ViewBag which is used as a temporary storage which can then be passed and used by our ASP.NET MVC View.  The code shown in Figure 11 creates a ViewBag variable called Message and stores a Hello World message in this ViewBag variable. You can then display this message inside the View by using Razor syntax as shown in Figure 12. Note that when typing Razor code inside the View you need to preappend it with the @ sign.

Figure 11 - ViewBag

Figure 11 – ViewBag

Figure 12 - Razor inside View

Figure 12 – Razor inside View

Now run the application, type in http://localhost/Home/Test, and you see that the Hello World message is correctly displayed, as shown in Figure 13.

Figure 13 - View with message

Figure 13 – View with message

So enough for this blog…. I hope you found it useful.