Creating a simple ASP.NET MVC project (Part 1) in 23 steps

Panthmadan
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 9756 red flag
Rating: 4.67 out of 5  
 3 vote(s)

In this article we will create a simple ASP.NET MVC Project in 23 Steps.

Introduction :

After reading lot of articles on the web on MVC, some are moderate some are too good and some are above the level for which you have to be experienced. We don’t find an article which is very simple and clears our fundamentals, the way each and every person mental thought is different. In this article an attempt is made to explain how do we create a simple form with insert in Database using EntityFramework in MVC.

Many of the students and freshers who are technical buff they sometimes really find it cumbersome to find the relevant software. The software we will be using here is Microsoft Visual Studio 2013 and SQL Server Management Studio.

The below URL’s will direct you to the download page :

SQL Server 2008 :https://www.microsoft.com/en-in/download/details.aspx?id=7593

MS Visual Studio :https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx

Hope at the end you will be able to create your own form and insert it into Database.

Download source code from here for the article.

Also side by side with this article, it's recommend to follow the below ASP.NET MVC youtube video.

Step 1:

Download MS Visual Studio from the above link and Install it.

Step 2 :

Download SQL Server 2008 from the above link and Install it.

Step 3 :

Once we are done with Installation procedure of Visual Studio and SQL Server, we are ready to start our project.

Open Visual Studio and follow the below steps.

Step 4 :

Go to File >> New >> Project>> Select ASP.NET Web Application >> Title the Name >> Click on OK

Step 5 :

After the project type is selected. We need to choose the template. Here we will select an empty template because we have to write the code for each and every method.

Select Empty >> Check MVC (reference) >> No Authentication >> Click on OK

Step 6 :

A new project of type MVC will be created with a solution file. Every project in Visual Studio is termed as Solution. Solution contains all the files. We can view it by View >> Solution Explorer. We can see the default folders for Model, View and Controller.

Step 7 :

Lets Add a controller to our project. Controller will only include the methods which will redirect to particular Views. These methods are called as Actions it has various return types.

Right click on Controller Folder >> Add >> Controller >> Select MVC5 Controller – Empty >> Click on Add >> Give the Controller Name >> Click on Add

Note : Controller name has to appended with Controller as seen in the above screen shot.

Step 8 :

As soon as a controller file is created, A folder inside View folder is been created with the same name. So all the view for this controller has to be inside University View Folder. If there a common view file for other controller we can save it in Shared Folder inside View Folder.

Step 9 :

Once we have added the Controller. We need to add the properties for our project. So will create a Model file inside Model Folder. This file will only consist of the properties and the attributes for the project. For this project we can Add Reg.No, Name and City.

Right click on Models Folder >> Click on Add >> Choose Class File >> Give the Name >> Click on Add.

Step 10 :

Lets add properties to our University Model Class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; // Importing Namespace

namespace MyApp.Models
{
    public class University
    {
        [Key]
        public int ID { get; set; } //Declaring Primary Key (Data Annotations)

        public string RegNo { get; set; } //Registration ID 
        public string Name { get; set; } // University Name
        public string City { get; set; } // City

    }
}

The above code is for the University Model Class.

Step 11 :

After the Model Class is created we will have to create View files which will be of type .cshtml which will be redirected once it invokes the Action method from Controller. We will need two View’s

One Form where we will have a link to Insert University

Second Form where we will have the University Details Form

Lets begun with First Form “Index.cshtml”

Right Click on University Folder inside View directory >> Add >> View >> Give Name >> Uncheck “Use a Layout page” >> Click on Add

Step 12 :

Lets go the Controller file where we have Index method.

namespace MyApp.Controllers
{
    public class UniversityController : Controller
    {
        //
        // GET: /University/
        public ActionResult Index()
        {
            return View();
        }
    }
}

The parameter inside the View method is empty because we have the same name of the View as the Action method. Whenever this action method is invoked the corresponding View is opened.

Step 13 :

Lets create a the Insert Form for University.

Right Click on University Folder inside View directory >> Add >> View >> Give Name >> Uncheck “Use a Layout page” >> Click on Add

The below shows the hierarchy of the files for the project.

Step 14 :

Add elements and attributes to “Add University.cshtml” file. To create a form we will use HTML tags.

<body>
<div>
<formaction="Save"method="post">
<h2> Add A UNIVERSITY</h2><hr/>

            Registration No : <inputtype="text"name="RegNo"><br/><br/>
            University Name : <inputtype="text"name="Name"><br/><br/>
             City :<inputtype="text"name="City"><br/><br/>
<inputtype="submit"value="Add University"/>
</form>
</div>
</body>

Step 15 :

Add elements and attributes to “Index.cshtml” file. To create a form we will use HTML tags.

<body>
<div>
<h1><ahref="Create"> Add  a New University </a></h1><br/>
</div>
</body>

Also to redirect to this page we will be adding a new Action Method in Controller File with “Create” action method.

publicActionResult Create()
        { 
return View("AddUniversity"); // Will direct to AddUniversity.cshtml.
        }

Step 16 :

Our Model, View and Controller is ready. But when we run this project we are unable to add it to our Database. So here we need to create a DB connection using Entity Framework which sits on the top layer of ADO.NET. It is nothing but an ORM tool which helps to relate the object to the model. Object Relational Model - ORM

To use Database Connection we need to import Entity Framework Library. So we have to download it using NuGet Packages.

Right Click on Solution folder >> Manage NuGet Package Solution >> Search for Entity Framework >> Click on Install.

Step 17:

Once we are done with Installation we can see the Entity Framework in Reference Folder inside our Solution Directory.

We will use Entity Framework for our Database Connection and will create Data Access Layer

Right Click on “MyAPP” >> Add New Folder >> Name it “DAL”

Step 18 :

After creation of DAL folder lets add a DAL file.

Right click on DAL folder >> add >> Class >> Name it accordingly >> Click on Add

The below code is for the DAL class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MyApp.Models; // Importing Model Class
using System.Data.Entity; // Using Entity Framework

namespace MyApp.DAL
{
    public class UniversityDAL : DbContext //Using Interface DBContext
    {
        public DbSet<University> Universities { get; set; } //DataBase Set

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<University>().ToTable("University Table"); // Auto Creation of Database
        }
    }
}

Step 19 :

We need to configure the connection string in our WEB.config file.

<connectionStrings>
<addconnectionString="Data Source=.;Initial Catalog=University;Integrated 
Security=True"
providerName="System.Data.SqlClient"
name="UniversityDAL"/>

Parameter :

ConnectionString : Provide the connection string

Provider Name : Type of Databse

Name : Name of the DAL class

Step 20 :

Populating the Database values on webpage in Tables.

“Index.cshtml”

@using MyApp.Models
@model List<University>
@{
Layout = null;
}

<!DOCTYPEhtml>

<html>
<head>
<metaname="viewport"content="width=device-width"/>
<title>Index</title>
</head>
<body>
<div>
<h1><ahref="Create"> Add  a New University </a></h1><br/>
<tableborder="1">
<tr>
<th>Reg No</th>
<th>University Name</th>
<th>University City</th>
</tr>
@foreach (University item in Model)
{
<tr>
<td>@item.ID</td>
<td>@item.Name </td>
<td>@item.City </td>
</tr>
}
</table>
</div>
</body>
</html>

Step 21 :

Modifying Controller Class to Pass the Object.

	public ActionResult Index()
        {
            UniversityDAL udal = new UniversityDAL();
            List<University> ulist = udal.Universities.ToList<University>();
            return View("Index",ulist);
        }

        public ActionResult Create()
        { 
           return View("AddUniversity");
        }

        public ActionResult Save(University u)
        {
            if (ModelState.IsValid)
            {

                UniversityDAL udal = new UniversityDAL();
                udal.Universities.Add(u);
                udal.SaveChanges();

                List<University> list = udal.Universities.ToList<University>();
                return View("Index", list);
            }
            else
            {
                return View("AddUniversity");
            }

Step 22 :

Lets Execute the project:



Step 23 :

Checking Database


So now that you are done with insertion how about continuing with select , update and delete http://www.dotnetfunda.com/articles/show/3204/creating-a-simple-aspnet-mvc-project-part-2-edit-and-delete 
Page copy protected against web site content infringement by Copyscape

About the Author

Panthmadan
Full Name: Madan Panth
Member Level: Starter
Member Status: Member,MVP
Member Since: 12/15/2015 4:34:44 AM
Country: India

www.questpond.com
Learn MVC in 16 hours
Learn design pattern in 8 hours
Learn C# in 100 hours series
Learn MSBI in 32 hours
Learn SharePoint Step by Step in 8 hours

Login to vote for this post.

Comments or Responses

Posted by: Sheonarayan on: 12/22/2015 | Points: 25
Hi Madan,

The article looks great however the copy-paste of code snippets are messy. Step 18 - declaration of class, Step - 21 and remaining other steps where you have code snippets should be revisited again. Particularly Step 18 code will never execute as there is no space between the class name and modifiers.

Please correct the code snippets.

Also we would suggest you to copy-paste the code directly from Visual Studio so that indention would be maintained and the code snippet would look nice and easily readable.

Thanks
Posted by: Sheonarayan on: 12/23/2015 | Points: 25
Good job Madan. Now the code snippet looks much better, easy to read and understand.

Thanks and keep up the good work.
Posted by: Panthmadan on: 12/24/2015 | Points: 25
Thank You SheoNarayan for Encouraging me.
Posted by: Rajayadav on: 12/24/2015 | Points: 25
Nice explanation , Thanks for sharing

Login to post response

Comment using Facebook(Author doesn't get notification)