Click here to Skip to main content
15,877,857 members
Articles / Web Development / HTML

Learning MVC - Part 2: Creating MVC Application and Perform CRUD Operations Using LINQ to SQL

Rate me:
Please Sign up or sign in to vote.
4.95/5 (70 votes)
17 Mar 2015CPOL10 min read 200.6K   15K   151   43
Creating MVC Application & Perform CRUD operations using LINQ to SQL


In the first part of the tutorial series we got a glimpse of MVC. In this part we’ll focus on the practical implementation of MVC Pattern. I don’t need to explain about theory of MVC as we have already covered this in the previous article.

Our Roadmap 

We stick our agenda as follows:

Topics to be Covered

  1. Creating an MVC project from scratch.
  2. Adding Controllers, Views and Models.
  3. Creating sample database and use LINQ to SQL for communication.
  4. Perform CRUD operations in MVC application using LINQ to SQL.
  5. Understand ViewData, ViewBag and TempData.
  6. Model Validation by System.Component.DataAnnotation.

1. Creating MVC project

Step 1: Open Visual Studio 2010/2013 (I am using 2010). Go to File=> New=> Project and select ASP.NET MVC3 Web Application, as shown below:

Image 1

Image 2

Name the application as LearningMVC.

Step 2: A project template selection window will be opened, select Empty in that. Select View Engine as Razor and press OK.

Image 3

Step 3: Now our solution is ready with an empty MVC application.

Image 4

We can clearly see that the solution contains some extra folders in comparison to traditional ASP.NET web application.

We get Models, Views Controllers, and a Shared folder in the Views folder. The folders hold their respective MVC players model-view-controllers. The shared folder in Views contains the _Layout.cshtml, which can be used as the master page for the views we create.

We see the global.asax file that contains a default routing table, that defines the route to be followed when the request comes. It says that when the request comes to the Home controller, the Index action of that Home Controller has to be called.

Image 5

Actions are the methods defined in Controllers (that can be called defining a route). The Action methods can also contain parameters in the above mentioned figure. It says that the Home controller has an Action Index which contains an optional parameter ID.

When we run our application we get something as shown below:

Image 6

It says that the resource which we are looking for cannot be found. The request by default follows the default route as mentioned in global.asax, I.E. go to the controller Home and invoke method Index. Since we don’t have any of these yet, the browser shows this error.

Never mind, let's make the browser happy.

2. Adding Controllers, View and Models

Step 1: Create a My Controller by right clicking on Controllers folder and add a controller named My. Add the controller with empty read/write actions, and it will give us a class with few default generated actions.

Image 7

Image 8

Note that there are two Actions for every Action name, one is for Get i.e. when view loads for first time, and second one is for POST, when View is submitted with some data.

Change global.asax RegisterRoutes method:

public static void RegisterRoutes(RouteCollection routes)

              "Default", // Route name
              "{controller}/{action}/{id}", // URL with parameters
              new { controller = "My", action = "Index", id = UrlParameter.Optional } // Parameter defaults


Note: we have changed the name of controller as per our added controller.

Step 2: We can see that we have Actions but they return a View, so we need to create Views for them. But before this we’ll create a Model named User for our Views. Right click on the Model folder add a class named User.

Image 9

Add following the properties to the User class:

Image 10

Now our model is created and we can create Views bound to this particular model.

Step 3: Go to controller, right click on empty Actions of the controller and from the context menu select AddView on the top. By default the View name is same as of Actions name.

e.g. For Details,

Image 11

Select Viewname as Details, Model class as User, and Scaffold Template as Details. This template specifies the role of the View. This view will show the details of the User(entity). Click add.

Likewise perform this operation for all the Actions, and create Views.

Note that Views are automatically added to the Views folder under My folder (auto created as per the Controller’s name). This is to maintain a particular structure for MVC, so that we don’t have to take overhead to maintain it.

Image 12

Image 13

Image 14

Image 15

Now we have controller as well as Views, so if we run the application we get.

Image 16

i.e. Index Action of our My controller is Fired that returned Index View. Image 17

3. Creating sample database and use LINQ to SQL for Communication.

Our MVC application is ready, but rather than displaying dummy data I run the application talking to a database so that we can cover a broader aspect of the application.

Step 1: Create a database, script is given in the attachment, just execute it over SQL Server 2005/2008.

Step 2: Add new Item to the solution, and select LINQ to SQL class, call it MyDB.dbml.

Image 18 

Our Solution looks like:

Image 19 

Step 3: Open Server explorer of Visual Studio, Open a connection, by providing Server name and existing database name in Server Explorer Open Connection window.

Image 20 

Click OK. Our solution looks like: 

Step 4: Drag the User table to DBML designer window, we get the table in class diagram format in designer window.

Image 21 

When we open MyDB.designer.cs, we get the MyDBDataContext class. This class holds the database User table information in the form of Class and Properties. For every column of the table, properties are created in the class, and we can use these properties to get/set values from/in database.

4. Perform CRUD operations in MVC application using LINQ to SQL

We now have a database, a context class to talk to the database and an MVC application to perform CRUD operations in database using the context class.

Step 1 Read

  1. Go to Index Action, make an instance of context class. We can get all the table and column names in that context’s instance.
  2. Make a query to display all the records on the Index view.
  3. Populate the User Model that we created earlier, and pass it to the Index view (Index View will be of List type Item template).

 Image 22

Image 23

When we run the application, we get an empty list, I.E. we don’t have records in database.

Image 24 

Step 2 Create

  1. First write code for creating a user. For the instance of Get Action of create, always an empty view will be returned. 

    Image 25
  2. When we post some data upon clicking the submit of Create then we need to make a data entry in the table for creating a new user. 
  3. When the form posted, it fires a Post Action of Create with the already bound User model properties to view fields. We’ll retrieve these model properties and make an instance of context class populate context User and submit to the database.

    Image 26
  4. Redirect action to the Index, and now a record will be shown on the Index View. We have successfully created a user.

    Image 27
  5. In database:

    Image 28 

Step 3 Update

Step 4 Delete

Now that we can perform the update and delete by ourselves, below are the screens for Update and Delete.

Edit Code: 


Image 29 


Image 30

Get Action View of Edit:

Image 31

Edited few fields:

Image 32 

Update reflected in database:

Image 33 

Code to show details of a particular user:

Image 34 

Details Screen:

Image 35 

Note: Details Action do not have POST one, as nothing to post to controller.

Likewise for Delete: 


Image 36 

Back to List after Delete:

Image 37 

In database after delete:

Image 38 

Yes, all the CRUD operations done.Now we know MVC. Image 39

There are few basic scenarios that I want to discuss before finishing with the First Part, like passing data from Controller to Views, between Controllers etc and about Model validation.

5. Understand ViewData, ViewBag and TempData

I wanted to take this topic as there is much confusion Image 40 regarding these three players.

MVC provides us ViewData, ViewBag and TempData for passing data from controller, view and in next requests as well. ViewData and ViewBag are similar to some extent but TempData performs additional roles. Let's get key points on these three players:

ViewBag & ViewData

I have written sample test code in the same application which we are following from the beginning,

  • Populate ViewData and ViewBag on Index action of My Controller

    Image 41
  • Code in View to fetch ViewData/ViewBag

    Image 42
  • When run the application, we get on screen

    Image 43 

Following are roles and similarities between ViewData and ViewBag:

  • Maintains data when move from controller to view.
  • Passes data from controller to respective view.
  • Their value becomes null when any redirection occurs, because their role is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Differences between ViewData and ViewBag (taken from a blog):

  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • ViewData requires typecasting for complex data type and check for null values to avoid error.
  • ViewBag doesn’t require typecasting for complex data type.


TempData is a dictionary derived from the TempDataDictionary class and stored in short lives session. It is a string key and object value.

It keep the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain data when we move from one controller to another controller or from one action to other action. In other words, when we redirect Tempdata helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when we are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. Generally it is used to store only one time messages like error messages, validation messages.

I added a TempData in Edit Action as:

        public ActionResult Edit(int? id, User userDetails)
            TempData["TempData Name"] = "Akhil";

And when View redirected to Index Action.

Image 44 

I.E. I get the TempData value across Actions.

6.Model Validation

We can have many methods for implementing validation in our Web Application Client Side, Server Side etc…

But MVC provides us a feature with which we can annotate our Model for validation by writing just one/two line of code.

public int UserId { get; set; }
        [Required(ErrorMessage = "FirstName is required")]
        public string FirstName { get; set; }
        public string LastName { get; set; }

Now when we run the application, and try to Edit/Create user without specifying FirstName, we get

Image 45

Surprised!? Yes model validates itself with these annotations. There are many more validators like required field one that I used.

Do not forget to include using the System.ComponentModel.DataAnnotations; Namespace, when using Model Validation. This is the namespace that holds classes used for validation.


Image 46

Now we know what MVC is, how to Implement it, its advantages, CRUD operations in MVC. Upcoming parts of the tutorial will be focusing on more advanced topics like EntityFramework, Repository Pattern, Unit Of Work Pattern. Code First Approach.

Happy coding :) 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
India India
Akhil Mittal is two times Microsoft MVP (Most Valuable Professional) firstly awarded in 2016 and continued in 2017 in Visual Studio and Technologies category, C# Corner MVP since 2013, Code Project MVP since 2014, a blogger, author and likes to write/read technical articles, blogs, and books. Akhil is a technical architect and loves to work on complex business problems and cutting-edge technologies. He has an experience of around 15 years in developing, designing, and architecting enterprises level applications primarily in Microsoft Technologies. He has diverse experience in working on cutting-edge technologies that include Microsoft Stack, AI, Machine Learning, and Cloud computing. Akhil is an MCP (Microsoft Certified Professional) in Web Applications and Dot Net Framework.
Visit Akhil Mittal’s personal blog CodeTeddy (CodeTeddy ) for some good and informative articles. Following are some tech certifications that Akhil cleared,
• AZ-304: Microsoft Azure Architect Design.
• AZ-303: Microsoft Azure Architect Technologies.
• AZ-900: Microsoft Azure Fundamentals.
• Microsoft MCTS (70-528) Certified Programmer.
• Microsoft MCTS (70-536) Certified Programmer.
• Microsoft MCTS (70-515) Certified Programmer.

This is a Collaborative Group

780 members

Comments and Discussions

GeneralMy vote of 4 Pin
Ujjval Shukla13-Sep-15 21:31
Ujjval Shukla13-Sep-15 21:31 
GeneralRe: My vote of 4 Pin
Akhil Mittal13-Sep-15 21:35
professionalAkhil Mittal13-Sep-15 21:35 
QuestionOutdated MVC version Pin
yuriygo1-Sep-15 10:43
yuriygo1-Sep-15 10:43 
AnswerRe: Outdated MVC version Pin
Akhil Mittal1-Sep-15 17:53
professionalAkhil Mittal1-Sep-15 17:53 
QuestionMy Vote 5 Pin
Dharmesh .S. Patil1-Jul-15 22:25
professionalDharmesh .S. Patil1-Jul-15 22:25 
AnswerRe: My Vote 5 Pin
Akhil Mittal1-Jul-15 23:20
professionalAkhil Mittal1-Jul-15 23:20 
QuestionProblem in creating view Pin
Hetzy15-Apr-15 13:19
Hetzy15-Apr-15 13:19 
AnswerRe: Problem in creating view Pin
Dharmesh .S. Patil1-Jul-15 20:16
professionalDharmesh .S. Patil1-Jul-15 20:16 
GeneralRe: Problem in creating view Pin
Akhil Mittal1-Jul-15 21:11
professionalAkhil Mittal1-Jul-15 21:11 
GeneralRe: Problem in creating view Pin
Dharmesh .S. Patil1-Jul-15 22:26
professionalDharmesh .S. Patil1-Jul-15 22:26 
QuestionRecord Not showing on index view Pin
Brittle161825-Mar-15 20:51
Brittle161825-Mar-15 20:51 
AnswerRe: Record Not showing on index view Pin
Brittle161825-Mar-15 22:03
Brittle161825-Mar-15 22:03 
GeneralRe: Record Not showing on index view Pin
Akhil Mittal30-Mar-15 0:29
professionalAkhil Mittal30-Mar-15 0:29 
GeneralRe: Record Not showing on index view Pin
Brittle161831-Mar-15 20:46
Brittle161831-Mar-15 20:46 
GeneralRe: Record Not showing on index view Pin
Akhil Mittal1-Apr-15 18:37
professionalAkhil Mittal1-Apr-15 18:37 
QuestionMissing My folder below Views Pin
Member 1122788123-Mar-15 5:15
Member 1122788123-Mar-15 5:15 
AnswerRe: Missing My folder below Views Pin
Dzung Van9-Aug-15 15:43
Dzung Van9-Aug-15 15:43 
GeneralGood! Pin
Patrick Makanga18-Mar-15 7:37
Patrick Makanga18-Mar-15 7:37 
GeneralRe: Good! Pin
Akhil Mittal18-Mar-15 18:36
professionalAkhil Mittal18-Mar-15 18:36 
GeneralRe: Good! Pin
Akhil Mittal18-May-15 18:55
professionalAkhil Mittal18-May-15 18:55 
QuestionNot getting LINQ to SQL template, after doing add new item Pin
Vivek S Kale5-Dec-14 2:45
professionalVivek S Kale5-Dec-14 2:45 
QuestionVery Good Article Pin
ashishjiwaji200626-Nov-14 23:11
ashishjiwaji200626-Nov-14 23:11 
AnswerRe: Very Good Article Pin
Akhil Mittal27-Nov-14 1:33
professionalAkhil Mittal27-Nov-14 1:33 
AnswerRe: Very Good Article Pin
Akhil Mittal18-May-15 18:55
professionalAkhil Mittal18-May-15 18:55 
GeneralMy vote of 3 Pin
Prachi_G6-Jul-14 9:16
Prachi_G6-Jul-14 9:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.