Wednesday, February 13, 2013

Start With MVC Application Part 1

Before we starting to create MVC Application we required customer table on which we create our application. So first create customer table as show in below


CREATE TABLE [dbo].[tblCustomer]
(
[Id] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](50) NOT NULL, [Address] [varchar](500) NOT NULL, [City] [varchar](50) NOT NULL,[State] [varchar](50) NOT NULL,[Country] [varchar](50) NULL, [Phone] [varchar](15) NULL, [EmailId] [varchar](50) NULL,
CONSTRAINT [PK_tblCustomer] PRIMARY KEY CLUSTERED 
( [Id] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GO




We creating our MVC Application with Visual Studio 2010. Start your visual studio, from File menu select New Project as shown in below. Select ASP.NET MVC 2 Web Application template (other wise download template from http://www.asp.net/mvc) give name MyFirstApplication and click on Ok in next screen skip Unit Test Project Creation.


Right click on models folder and LINQ to SQL Classes with name Application, select database and drag n drop tblCustomer on design surface area with this step we completed our prerequisite of our application




Create customer folder under views folder in which we are going to store all customer related methods. Now we going to create CRUD methods for Customer using MVC. First we create controller for customer for this right click on Controllers folder and add controller with name CustomerController. This is one of the most important step while creating MVC Application.




When we create controller Index method created it contains Index method. We use this method to show list of all record from that controller. Add following code in Index method which returns list of customers.


 public ActionResult Index()
 {
       var Customers = from vcustomer in this.dbContext.tblCustomers 
                                      select vcustomer;
      return View(Customers);
}


Right click on Index method then select Add View menu from pop menu. In Add view window set parameter as shown in the picture below




After clicking on Add button Visual Studio create Index.Aspx page in Views/Customer folder which will be our landing page for Customers. Now we have to add customer menu in master page for this open Site.Master page from Shared folder.  In master page add Html.ActionLink for customer as shown below

                <ul id="menu">              

                    <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
                    <li><%= Html.ActionLink("Customer", "Index", "Customer")%></li>
                    <li><%= Html.ActionLink("About", "About", "Home")%></li>
                </ul>


After Adding this compiled and run the web application. In next blog we going to study how to implement CRUD methods for customer object.






No comments:

Post a Comment