LOGIC Library

This site is the Logic involvement in sharing expertise and skills acquired in daily work. The goal is to create a solid knowledge base and share best practices in software development and systems management.

More info about us can be found on logicsistemi.it.

ASP.NET MVC 4 tutorial for web developers - part 7

In the last post we create a List of users retrieved from the database.

It's now time to display this list in a view and complete the first part of this tutorial: displaying database data.

Views and models

In the previous post we end the controller method with the following instruction:

return View(users);

The Controller.View method creates a ViewResult object that renders a view to the response. By passing an object to this method we can specify a model that will be available in the view.

If our purpose is only to display data, the model don't need any particular method and can be, conceptually, any kind of object that carry information. In our example the model is a simple List of strings.

Microsoft explains the difference between a dynamic or a strongly typed view. Because we have choose to store data in a simple list of string, we don't have a particular object to use as a model class, so we opt to the dynamic type of view. We will come back to this concept when we will introduce a real model.

In the Views folder we can create a new folder called Users. This is is the folder that will contains all views related to the Users controller.

By right clicking on it we can choose to add a new view leaving the strongly typed option unchecked.

part7 add view

The creation of a view is a very simple task, so you can also simply create an Index.cshtml file in the Users folder with this content:

<h2>Users list</h2>
<ul>
@foreach (string item in Model)
{
<li>@item</li>
}
</ul>

The Model object on the line 4 is instantiated using the object passed to the View method, so for us is a list of string and we can easily iterate on it.

Improving the example with a model

To complete this post we add a real model. This is, for now, a simple object, with the right properties. This object, in the next posts, will be extended with the methods to add, modify and delete records.

We add in the controller class a piece of code used only to understand how MVC works. We will see that this code has already been added for us by Visual studio in another file.

Open the Controller class file and modify it in the following way:

namespace MyTasks.Controllers{
    public class User
    {
        public int UserId;
        public string UserName;
    }
    public class UsersController : Controller
    {
        //
        // GET: /Users/
        public ActionResult Index()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            List<User> users = new List<User>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                // Open the connection
                conn.Open();
                string sql = "SELECT * FROM UserProfile";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        User tempUser = new User();
                        tempUser.UserId = Convert.ToInt32(reader["UserId"]);
                        tempUser.UserName = reader["UserName"].ToString();
                        users.Add(tempUser);
                    }
                }
                conn.Close();
            }
            return View(users);
        }...

We've added a User class and we have modified the Index method to create a list of User object instead of simple strings.

This process can be extended to every database table, so you have now a simple template you can use in every situation.

The view become the following:

<h2>Users list</h2>
<ul>
@foreach (MyTasks.Controllers.User item in Model)
{ <li>@item.UserId - @item.UserName</li>
}
</ul>

Try the code be clicking on the run button.

Intellisense and scaffolding

Using an object that represents our table, you can benefit of the Intellisense function of VisualStudio when you need to access a field.

This is a very nice feature that can speed up your productivity.

Intellisense is not the only feature Visual Studio offers us. If you compile the project and then you try to add a new view, you can notice that the User class has been added to the model classes available to create a strongly typed view!

Next time we will go a little out of a standard MVC tutorial, by adding to this page the JQGrid plugin.

Comments   

 
#1 Royce Roy 2013-06-06 16:47
This is awesome!! really helpful for me. Thanks for sharing with us. Following links also helped me to complete my task.

http://www.mindstick.com/Articles/63bce1d2-3d08-48a1-a325-57754b1f000e/?Creating%20a%20simple%20model%20using%20ASP%20NET%20MVC4

http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-model
Quote
 

Add comment


Security code
Refresh