Tuesday, January 7, 2014

Step By Step How to create an Action Method to list all table items

        By Carmel Schvartzman


In this tutorial we'll learn how to create an Action Method to list all database table entries  in ASP.NET MVC 4
An Action method is a public method in a Controller, called in response to an user interaction. When a user send a request to an MVC app, the MVC framework find the appropriate Controller routing the request to it, and calling an Action method. This Action method returns an ActionResult object, which can be one of the following:
1. ViewResult : renders an MVC View
2. PartialViewResult : renders a section of a View
3. FileResult : returns binary data in the response
4. JsonResult : returns serialized Json object
5. JavaScriptResult : returns a script to be executed in the user browser
6. RedirectResult : redirects to another Action by URL
7. RedirectToRouteResult : redirects to another Action

There is also an EmptyResult, to return null.
Every public method in a Controller is suposed to be an Action. We can place private methods in a Controller, and if we need a public method that is not an Action, it must be decorated by an NonActionAttribute, which is translated by MVC to an 404 error (Page Not Found).

An Action method can handle different HTTP Verbs by using the AcceptVerbsAttribute, or the following more specific attributes:
1. HttpGetAttribute (for retrieving data)
2. HttpPostAttribute (for creating new entries)
3. HttpPutAttribute (for updating data)
4. HttpDeleteAttribute (for deleting)

When an Action method returns a View, we can pass data to the View using the ViewDataDictionary collection, this way:
                ViewData["Some Key"] = "Some Value";

Also , the View object supports getting any strongly-typed object as an argument:
                return View(someObject);

In the case an Action must pass data to another Action, this data is stored in a Session collection named TempDataDictionary:
               TempData["SomeKey"] = someObject;

This is useful while redirecting to another Action, or when sending a message to another Action in case of errors.


We'll add an Action Method to list all table entries  in ASP.NET MVC 4 , resulting in the following :


Let's say we have an MVC app connected to a database with an Entity Framework data model. First we'll create a DataRepository which supports retrieve actions. Create a new class BlogRepository:



In the new class, create a property with only "get" function to worry for creating the Data Model context:


Create a new method to retrieve the posts of the blog:


Add the code to retrieve the posts collection from Cache, if existing, or from the database, storing the new retrieved data in memory. The code will store the posts list in Cache for 30 minutes :


Now we're ready to create our Controller and its Action methods. Add a new Controller named "BlogController":




The template to be used will be "MVC Controller with empty read/write actions":


Open the new Controller and find the Index Action:


Write the following code to retrieve the posts list from the Repository:


Now let's add a View to render the list:


Opt for creating a strongly-typed View, with the Blog Model:



The Scaffold Template must be "List" in this case:


The "Index" View inside the "Blog" folder has been automatically created:

The Index .cshtml file receives an IEnumerable<Blog> collection from the Controller:


In order to add a new link to the Menu, open the _Layout.cshtml file and add the following entry:


Now let's see how our Action method works. Debug the project (F5), and browse to the "Blog" page :


If you insert a breakpoint inside the Repository, you'll see that the Entity Framework is called to retrieve the posts list:


We get the posts list:


Now refresh the web page:



The Repository is entered but this time the data is stored in Cache, so we don't need to retrieve data from the database.

In this tutorial we have learned how to create an Action Method to list all database entries  in ASP.NET , MVC 4, using a Repository with caching support.

That's all!! 
Happy programming.....


כתב: כרמל שוורצמן