Creating Model with Data Access Class – ASP.NET MVC2

Its often a discussion whether to choose ASP.NET MVC or Web form and which one is better, also there are times when I have seen people thinking that I know web form so well if I make a switch what's going to happen if I make a switch and will it worth for because I have spend years and years becoming ninja in web form technology and now when it feels that its almost there, here comes new technology to learn. Well let me tell you something that this has been one of the thing that was with me as well, but moment I started exploring features of MVC I realized that Microsoft team has done such an amazing work on putting this new technology together that all you have learned and spend years learning will not just go in vain. All good things about web forms are here in one form or the other.

Today we are going to look at one such example. We are going to use business logic and data access layer as model in order to retrieve data from database and show it on presentation layer.

ScreenShot:

So in order to get started, we will create a class and write a product class and data access code from Adventure works database to do this right click on Model folder -> Add -> Class with name Products.cs:

Code: Products.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Configuration;

using System.Data;

using System.Data.SqlClient;

 

namespace DataAccessMVCApp.Models

{

public class Products

{

public IList<Product> GetAllProducts()

{

string strConfig=WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

List<Product> prodColl = new List<Product>();

using (SqlConnection conn=new SqlConnection(strConfig))

{

 

SqlCommand cmd = new SqlCommand();

cmd.Connection = conn;

cmd.CommandText = "SELECT [ProductID],[Name],[StandardCost],[ProductNumber] FROM [AD].[dbo].[Products]";

cmd.CommandType = CommandType.Text;

conn.Open();

SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

while (rdr.Read())

{

Product prod = new Product();

prod.ProductID = Convert.ToInt32(rdr["ProductID"]);

prod.Name = Convert.ToString(rdr["Name"]);

prod.StandardCost = Convert.ToDouble(rdr["StandardCost"]);

prod.ProductNumber = Convert.ToString(rdr["ProductNumber"]);

prodColl.Add(prod);

}

conn.Close();

rdr = null;

cmd = null;

}

return prodColl;

}

}

 

public class Product

{

public int ProductID { get; set; }

public string Name { get; set; }

public double StandardCost { get; set; }

public string ProductNumber { get; set; }

}

}

 

Next let's add controller for product:

So right click on Controllers folder -> Add -> Controller with name ProductController.cs

Code: ProductController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

// Here we are adding reference to our models so we can create its instance and return data in view

using DataAccessMVCApp.Models;

 

namespace DataAccessMVCApp.Controllers

{

public class ProductController : Controller

{

//

// GET: /Product/

 

public ActionResult Index()

{

Products pdb = new Products();

var resultData = pdb.GetAllProducts();

return View(resultData);

}

 

}

}

 

After this it's time to add view for this controller, so in order to do that right click inside Index() of controller above and select Add view than set following properties:

Note: If you don't see any Product Model inside view data class drop down than try to build your project first and try again

What this will do for us, is it will create new folder with name Product with index.aspx file inside views folder:

Update your code based on your need to look like following:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"

Inherits="System.Web.Mvc.ViewPage<IEnumerable<DataAccessMVCApp.Models.Product>>" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

    List of Products

</asp:Content>

 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

 

<h2>List of Products</h2>

 

<table>

<tr>

<th>Product ID</th>

<th>Product Name</th>

<th>Product Std Cost</th>

<th>Product Number</th>

</tr>

 

<% foreach (var item in Model) { %>

 

<tr>

<td>

<%:item.ProductID %>

</td>

<td>

<%:item.Name %>

</td>

<td>

<%:string.Format("{0:c}",item.StandardCost) %>

</td>

<td>

<%:item.ProductNumber %>

</td>

</tr>

 

<% } %>

 

</table>

 

 

 

</asp:Content>

 

 

Tags: , ,

ASP.NET | MVC