ASP.NET MVC 5 -Tutorial-CRUD Operations in MVC

Table of Contents
  • Abstract
  • Introduction to MVC
  • Why MVC?
  • ASP.NET MVC over ASP.NET Web-Forms
  • Overview of Model View Controller

    • What is a Model?
    • What is a View?
    • What is a Controller?
  • Overview working of MVC
  • Overview of routes collection 

    • What is route?
    • What happened at runtime? 
  • Conclusion
  • Special thanks to audience
Abstract
In this article we will discuss what was presented in the session for ASP.NET in Delhi Developer's day held on November 15, 2014.

It was an awesome event where all developers united under a common platform. All enjoyed and tried to explore their knowledge of ASP.NET MVC.

In this session, we covered the very basics of ASP.NET MVC, that is a very important build foundation of the ASP.NET MVC framework.

Here are the topics we covered in this session:
  • Introduction to MVC.
  • Why MVC.
  • Reason to choose MVC against ASP.Net web forms.
  • Overview of Model View Controller.
  • Overview working of MVC.
  • Overview of routes collection.
  • Revisiting session.
  • Question / Answer / Suggestion.
Introduction to MVC
A background to ASP.Net MVC:
  • Based on ASP.Net.
  • A framework for Rapid Application Development (RAD), used to develop Web applications.
  • Is a composition of Model, View and Controller.
Is an open source and the code is available in Code Plex (In 2009 it was released under the Microsoft Public License and in 2012 it was released under the Apache License 2.0).

We can simply say that ASP.NET MVC is a framework that provides us the ability to create a web project, web application (called Rapid Application Development (RAD)).

Why MVC
Take a moment and think about the valuable Software Pattern Model-View-Controller. We can also predicts from the image that the MVC pattern divides a software application into three interconnected parts/components. Basically, it's a concept of separation (here just separation of internal representation of information from ways/logics/techniques how it is being represented to the end-user).

MVC
                  FIGURE 1: DEFINING MVC

As in the preceding image, let's elaborate on Model View Controller (MVC).
Controller can send commands/directions to the model to update its state as well as commands to the view.

Associated views and the controller are notified by the Model as in changes of its state.

The Model provides a specific result as an output upon the request of the View to represent:

DEFINING MVC
                                                            FIGURE 2: DEFINING MVC

Let's understand this from the above associated image.

In simple words, we can say that MVC is providing a facility to make our layers separate that are separated and interacting with each other.

ASP.NET MVC over ASP.NET Web-Forms
There are numerous reasons to choose ASP.Net for web development over ASP.Net Web Forms:
  • ASP.Net MVC is a web framework and is based on the MVC pattern.
  • No view state (performance is better in ASP.Net MVC).
  • Completely testable.
  • Integration with the client side (easily handshakes with client-side scripting like jQuery and so on).
Flexibility (provides various view engines that render HTML; Razor View Engine is the most famous).

Let's think of a scenario where we are writing an application in ASP.NET Web Forms. There are two classes for one thing. Let's say a default page that includes Default.aspx and Default.aspx.cs pages and our designer page.

A designer page has all the server control and aspx pages, that contain visualization of our server controls (UI part) and finally our cs page (class) contains all the functionality and other logic. Our class is based on an ASP.NET Page lifecycle (for complete details refer to: ASP.NET Page Life Cycle Overview).

We can't completely test our Web-Forms. To make it properly testable at some instance, we need to implement some other UI Design pattern such as MVP, MVVM or MVC.

If we are implementing the MVC UI Pattern to our Web Forms then why don't we use the ASP.NET MVC framework that already uses this pattern and provides everything required to create web apps?

Overview of Model View Controller
"This section of the session was a part of great discussion, what we learned until now. Please comment in this article what we discussed (all queries and so on). I'll update this section later."

Here is the conclusion that we discussed (for the ASP.Net MVC framework).

Models
  • A MVC Model is typically a class (of C# or VB.NET).
  • Both the controller and view can access the Model.
  • A Model can be used to pass data from a Controller to the View.
  • The main purpose of a View is to display the data in a page using the Model.
Views
  • A View is nothing but a page, you can say a web page, and it does not have code-behind
  • All page specific HTML generation and formatting can be done inside the View
  • A request to the View can be made only from a Controller's action method
Controllers
  • A Controller is typically a class (of C# or VB.Net) and inherits “system.mvc.controller”.
  • Within this class, methods can be implemented and are called action methods. These are responsible for responding to the browser and/or calling the Views.
  • The Controller class can access and use the Model class to pass data to the Views.
Overview working of MVC
In the following we will explore MVC more:

REQUEST RESPONSE
            FIGURE 3: REQUEST RESPONSE

High level overview says: the browser sends a request to ASP.Net MVC and it returns a response back to the browser (the request is a HTTP request and the response is a HTTP response).

WORKING OF ASP.NET MVC
                                                            FIGURE 4: WORKING OF ASP.NET MVC

In a broader way: The first request comes to the Route Tables then passes to a specific controller before interaction with the Model Binding. It goes through Authentication and Authorization and afterwards fires a specific Action Method and executes the results to the View.

Overview of routes collection
In simple words, the routes collection (we also can say Route table) is nothing but a collection of routes. 

Routes

A system works on a pattern matching mechanism. A route matches an incoming request to meet a specific pattern and allows once matched else denied.

What happens at runtime
At runtime, the routing engine uses a route table (contains various routes) to match incoming URLs with the defined route patterns (URL patterns).

ROUTE COLLECTION
                                                                  FIGURE 5: ROUTE COLLECTION

In the above image, the URL will be processed if any match is found else it will throw the HTTP Status code Not Found (404 error).

Example of typical route collections:
  1. public class RouteConfig  
  2. {  
  3.     public static void RegisterRoutes(RouteCollection routes)  
  4.     {  
  5.         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  

  6.         routes.MapRoute(  
  7.             name: "Default",  
  8.              url: "{controller}/{action}/{id}",  
  9.             defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
  10.             );  
  11.     }  
  12. }  
Conclusion
In this very first session we covered: ASP.Net MVC Series For Beginners: Part 1
  • Basics of MVC
  • Discussed MVC pattern
  • Discussed basics of MVC architecture
  • Discussed basics of route collection / route table
We will continue in the next session: 

This article will take you on a journey of MVC Create, Replace, Update and Delete (CRUD) operations. I'll show you step-by-step operations using simple images and charts. So buckle up for that journey.

Agenda
  • Overview
  • Introduction
  • Procedure

    • Creating a MVC Project
    • Adding EDM
    • DB Settings
    • Adding a controller
    • (Ref code Snippet)
    • Routing
  • Conclusion
Overview
This article will explain MVCs base operations rather than any fundamentals and anything like that so if you are new to MVC then I'll suggest you first explore the basics, it will hardly take a few hours then you can read this article.

In spite of these entire one more thing, I'm using MVC4 here for these operations. You can use any version but in the earlier versions, like in case of VS'8 and below you need to install templates first, then you can have fun.

Introduction

This article is all about ASP.NET MVC CRUD operations using Entity Data Model (DB First Approach). This will explain it in baby steps using images. One more interesting fact about this article is, you are not going to write even a single line of code.

Here we go.

Procedure
I am dividing this into 7 major steps, these steps will contain several sub steps. The major steps of this project are:



Step 1: Creating a MVC Project

Just click on File > New project.

On clicking New Project you will get a window like this, in that window does these tiny steps:





In this window simply fill in the project name depending on you; in my case it is "CRUDoperation" and then click on OK.



On clicking OK a window like this will pop up on your screen. 



In that window from Project Templates you have several options like:
  • Empty 

    (Simply a blank view)
  • Basic 

    (Contains a few options and a few folders)
  • Internet Template 

    (Contains all the folders for global use)
  • Intranet Template 

    (Contains all the folders but for a specific scenario)
  • Mobile Application 

    (For mobile app dev)
  • Web API 

    (Extra features of Razor, Routing and others)
  • Single Page Application 

    (For single page app dev)
  • Facebook Application 

    (Facebook app dev)
From those select Intranet Application and then from View Engine select Razor Engine View (it's the default actually).

Then after View Engine there is an option for Create a Unit Test Project, this option is for creating a step-wise unit test for your project. (Microsoft provides that functionality in the default in MVC. It's not mandatory to create a unit test project but in my case I am using it.)

Now just create a Test Project and click OK.



On clicking okay it will take a while to create the project.



Then you will get a window containing these folders:
  • Solution Explorer
  • Test Explore
  • Class View
  • Properties
From these options select Solution Explorer, click CRUDoperations, just click on that and you will get a view of this window.



Step 2: Adding EDM

(For data I am selecting ADO.Net Entity Data Model, you can select several other available options.)

Just do this procedure, right-click on CRUDoperation > Add New Item

Then follow this procedure, respectively:




Simply name your EDM model (in my case it's EDM) and then click OK.

Now you will get a pop-up window, named Choose Model Contents. This contains the following 2 types of model contents:
  • Generate from Database (DB first approach)
  • Empty Model (Modal first approach)
(In my case I am using the DB first approach (Generate from Database), just select it and click on "Next" )



On clicking Next, you will get a option Choose Your Data Connection, from here just select a connection string if you already have one or else you can go with New Connection.

Just click on New Connection.



Now set your connection properties as in the following:



Just fill in all the required details of your server and database and proceed further.



Microsoft has provided a beautiful option to check your connection, down the pop box. Just click on Test Connection, if everything until now will be smooth and clear then you will get a pop-up box saying- "Test connection Succeeded" as shown below.

(Otherwise you need to recheck your DB and server details again and try to establish the connection again and then you can check your connection.)



Now you can see the generated Data Connection in the box as shown below. Just select a few further settings like Security and march forward.

Just click on “Finish”.



On clicking Finish it will show a box saying Model Wizard, just select any of the wizards depending on availability (in my case I am selecting Entity Framework 5.0).

Click Next for further settings.



Step 3: Selecting you DB Settings
Now in this step just click on Table, dbo (as I already have a table in my DB, but if you created a Stored Procedure or view then select it respectively).

In model Namespace just leave it as it is or change it depending on you. In my case its TestDBModel, click Finish.



This will redirect you to a page containing a structure diagram of all the available tables in that select DB in step 3. You remove others depending on you (in my case it's Employee having the columns EmployeeId, FirstName, LastName, Age, Project and Address).

You don't need to do anything here, just chill it's more than half done.



You can see all these EDM files in the Solution Explorer, having all the required fields, pages and reference files of all your available tables with ".cs extension".



Note: Before proceeding to Step 5, build the project. It's recommended.

Step 4: Adding a Controller

For adding a controller do this procedure:



On clicking Add Controller, it will redirect to you to this window, having these fields:
  • Controller Name
  • Scaffolding Template
  • Model Class
  • Data Context Class
  • Views
Just modify entries depending on you. (My entries are shown below.) 

Now click Add.



It will redirect you to a page named "CRUDcontroller.cs" (as I modified it). This page contains all the CRUD operation related functions and two others, such as:
  • Index.cs
  • Details.cs
Reference Code | Snippet

This is of the CRUDcontoller.cs page that represents all the base operations with their respective get and set methods.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8.   
  9. namespace CRUDoperations.Controllers  
  10. {  
  11.     public class CRUDController : Controller  
  12.     {  
  13.         private TestDBEntities db = new TestDBEntities();  
  14.   
  15.         //  
  16.         // GET: /CRUD/  
  17.   
  18.         public ActionResult Index()  
  19.         {  
  20.             return View(db.EMPLOYEEs.ToList());  
  21.         }  
  22.   
  23.         //  
  24.         // GET: /CRUD/Details/5  
  25.   
  26.         public ActionResult Details(string id = null)  
  27.        {  
  28.             EMPLOYEE employee = db.EMPLOYEEs.Find(id);  
  29.             if  (employee == null)  
  30.             {  
  31.                 return HttpNotFound();  
  32.             }  
  33.             return View(employee);  
  34.         }  
  35.   
  36.         //  
  37.         // GET: /CRUD/Create  
  38.   
  39.         public ActionResult Create()  
  40.         {  
  41.             return View();  
  42.         }  
  43.   
  44.         //  
  45.         // POST: /CRUD/Create  
  46.   
  47.         [HttpPost]  
  48.         [ValidateAntiForgeryToken]  
  49.         public ActionResult Create(EMPLOYEE employee)  
  50.         {  
  51.             if (ModelState.IsValid)  
  52.             {  
  53.                 db.EMPLOYEEs.Add(employee);  
  54.                 db.SaveChanges();  
  55.                 return RedirectToAction("Index");  
  56.             }  
  57.   
  58.             return View(employee);  
  59.         }  
  60.   
  61.         //  
  62.         // GET: /CRUD/Edit/5  
  63.   
  64.         public ActionResult Edit(string id = null)  
  65.         {  
  66.             EMPLOYEE employee = db.EMPLOYEEs.Find(id);  
  67.             if (employee == null)  
  68.             {  
  69.                 return HttpNotFound();  
  70.             }  
  71.             return View(employee);  
  72.         }  
  73.   
  74.         //  
  75.         // POST: /CRUD/Edit/5  
  76.   
  77.         [HttpPost]  
  78.         [ValidateAntiForgeryToken]  
  79.         public ActionResult Edit(EMPLOYEE employee)  
  80.         {  
  81.             if (ModelState.IsValid)  
  82.             {  
  83.                 db.Entry(employee).State = EntityState.Modified;  
  84.                 db.SaveChanges();  
  85.                 return RedirectToAction("Index");  
  86.             }  
  87.             return View(employee);  
  88.         }  
  89.   
  90.         //  
  91.         // GET: /CRUD/Delete/5  
  92.   
  93.         public ActionResult Delete(string id = null)  
  94.         {  
  95.             EMPLOYEE employee = db.EMPLOYEEs.Find(id);  
  96.             if (employee == null)  
  97.             {  
  98.                 return HttpNotFound();  
  99.             }  
  100.             return View(employee);  
  101.         }  
  102.   
  103.         //  
  104.         // POST: /CRUD/Delete/5  
  105.   
  106.         [HttpPost, ActionName("Delete")]  
  107.         [ValidateAntiForgeryToken]  
  108.         public ActionResult DeleteConfirmed(string id)  
  109.         {  
  110.             EMPLOYEE employee = db.EMPLOYEEs.Find(id);  
  111.             db.EMPLOYEEs.Remove(employee);  
  112.             db.SaveChanges();  
  113.             return RedirectToAction("Index");  
  114.         }  
  115.   
  116.         protected override void Dispose(bool disposing)  
  117.         {  
  118.             db.Dispose();  
  119.             base.Dispose(disposing);  
  120.         }  
  121.     }  
  122. }  
You can see the controller info on the preceding page but if you want to see their views then simply click on Views, it will show you a separate folder named CRUD and all the pages for the CRUD operations.



You can see the razor engine functionality in any of the pages, as shown below. This page shows a view of the create page, I'll show you that page later in this article.



Step 5: Routing

Routing is itself a complex mechanism, but here I am showing you only the base access functionality. For that base functionality, follow this procedure:





On clicking Route.Config.CS it will redirect you to that window (below). You need to make some changes in that page such as:
  • Controller Name
  • Action
Entity Framework 
In my case I changed it to Controller = “CRUD”.

All other options are the default for the operation.



Just run that page and you will see a page like this. This is your default page of CRUD operations. You can access all the other options.



This is the base structure of the create page, as I was talking about in Step 5.

You can create entries from here.

Comments

AB InfoTech

reach out : abinfotechnology@gmail.com