SlideShare a Scribd company logo
Learning MVC-Part 2
Creating MVC Application&
Perform CRUD operationsusing LINQ to SQL
Introduction:
In firstpart of the tutorial series we got a glimpse of MVC. In this partwe’ll focus on practical implementation of MVC
Pattern. I don’tneed to explain about theory of MVC as we have already covered this in previous partof the article.
Our Roadmap:
We stick our agenda as follows,
Part1: Introduction to MVC architecture and Separation of Concerns.
Part 2: Creating MVC Application from scratch and connecting it with databaseusing LINQ to SQL.
Part 3: Connecting the MVC Application with the help of EntityFramework DB-Firstapproach.
Part 4: Connecting the MVC Application with the help of EntityFramework Code-Firstapproach.
Part 5: Implementing Repository Pattern in MVC Application with EntityFramework.
Part 6: Implementing a generic Repository Pattern and Unit Of Work pattern in MVCApplication with EntityFramework.
Topics to be covered:
1. Creating MVC projectfromscratch.
2. Adding Controllers, Views and Models.
3. Creating sample databaseand use LINQ to SQL for communication.
4. PerformCRUD 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:
Step1: Open VisualStudio 2010/2013,I amusing 2010.Goto File=>New=>Projectand select ASP.Net MVC3 Web Application, as
shown below,
Name the application as LearningMVC.
Step2: A projecttemplate selection window will be opened, select Empty in that.Select View Engine as Razor and press OK.
Step3: Now our solution is ready with an empty MVC application,
We can clearly see that the solution contains some extra folders in comparison to traditional Asp.Net web application.
We got Models, Views and Controllers folder and a Shared folder in Views folder. The folders as name denotes are used to hold the
respective MVCplayers model-view-controllers, theshared folder in Views contains the _Layout.cshtml, that can be used as the master
page for the views which we create.
We see the global.asaxfile that contains a default routing table, that defines the route to be followed when request comes, it says that
when request comes to Home controller, the Indexaction of that Home Controller has to be called,
Actions are the methods defined in Controllers, that can be called defining a route, the Action methods can also contain parameters, in
above mentioned figure, it says that Home controller has an Action Indexwhich contains an optional parameter id.
When we run our application, we get something as shown below,
Itsayethat the resourcewhich weare looking for can not be found.Therequestby default follows the default route as mentioned in
global.asax, i.e. go to controller Home and invokemethod Index.Sincewe don’thave any of these yet, the browser shows this error.
Never mind, lets make the browser happy.
2. Adding Controllers ,View and Models:
Step1: Create a My Controller by right clicking on Controllers folder and add a controller named My, add the controller with empty
read/write actions, it will give us a class with few default generated actions.
Note that there are two Actions for every Action name, one is for Get i.e. when view loads for firsttime, and second one is for POST,
when View is submitted with some data.
Change global.asaxRegisterRoutes method as,
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "My", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
Note: we havechanged the name of controller as per our added controller.
Step2: 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.Rightclick on Model folder add a class named User,
Add following properties to User class,
Now our model is created and we can create Views bound to this particular model.
Step3: 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,
Select Viewname as Details,Model class as User, and Scaffold Template as Details.This template specifies the role of the View, that this
view will show the details of the User(entity).Click add.
Likewiseperformthis operation for all the Actions, and create Views.
Note that Views are automatically added, to Views folder under My folder(auto created as per Controller’s name).This is to maintain a
particular structurefor MVC, so that we don’thave to take overhead to maintain it.
Now we have controller as well as Views, so if we run the application we get,
i.e. IndexAction of our My controller is Fired that returned IndexView.
3. Creating sample database and use LINQ to SQL for communication.
Our MVC application is ready but, rather than displaying dummy data, I would go for running the application talking to a
data base so that wecan cover wider aspect of the application.
Step1: Create a database, script is given in the attachment, justexecute it over Sql Server 2005/2008.
Step2: Add new Itemto the solution, and select LINQ to SQL class, call it MyDB.dbml
Our Solution looks like,
Step3:Open Server explorer of Visual Studio, Open a connection, by providing Server name and existing databasename in Server
Explorer Open Connection window,
Click OK.Our solution looks like,
Step4: Drag the User table to dbml designer window,wegetthe table in class diagram formatin designer window,
When we open MyDB.designer.cs, weget MyDBDataContext class.This class holds databseUser table information in the formof Class and
Properties.For every column of the table, properties are created in the class, and we can usethese 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 data base and a MVC application to performCRUD operations in databaseusing the
context class.
Step1 Read:
i) Go to IndexAction, makean instance of context class, Wecan get all the table and column names in that context’s instance.
ii) Make a query to display all the records on Indexview.
iii) Populate the User Model that we created earlier, and pass it to the Indexview(IndexView will be of List type Itemtemplate)
When we run the application, weget empty list, i.e. we don’t haverecords in database,
Step2 Create:
i)Firstwritecode for creating a user, for the firsttime for Get Action of create, always an empty view will be returned.
ii)When we postsome data on click of submitof Create, then we need to make a data entry in table for creating a new user.
iii)When formposted, it fires PostAction 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 submitto data base.
iv)Redirect action to Index, and now a record will be shown on the IndexView.We successfully created a user .
v) In database:
Step3 Update:
Step4 Delete:
Now we are smartenough to performupdate and delete by ourself, this I leave for reader’s understanding capabilities, below are the
screens for Update and Delete.
Edit Code:
Get:
Post:
Get Action View of Edit:
Edited few fields:
Update reflected in database:
Code to show details of a particular user :
Details Screen:
Note : Details Action do not have POSTone, as nothing to post to controller.
Likewisefor Delete:
Screen:
Back to List after Delete:
In databaseafter delete:
Yes, all the CRUD operations done.Now we know MVC.
There are few basic scenarios that I want to discuss beforefinishing with the First Part, like passing data fromController 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 regarding these three players.
MVC provides us ViewData, VieBag and TempData for passing data fromcontroller, view and in next requests as well. ViewData and
ViewBag are similar to someextent but TempData performs additional roles. Lets get key points on these three players:
ViewBag & ViewData:
I have written sampletest code in the sameapplication which we are following from the beginning,
- Populate ViewData and ViewBag on Indexaction of My Controller,
- Code in View to fetch ViewData/ViewBag,
- When run the application, we get on screen,
Following are roles and similarities between ViewData and ViewBag:
 Maintains data when movefrom controller to view.
 Passes data from controller to respectiveview.
 Their value becomes null when any redirection occurs , becausetheir role is to providea way to communicate between
controllers and views. It’s a communication mechanismwithin the server call.
Differences between ViewData and ViewBag (taken from a blog):
 ViewData is a dictionary of objects that is derived fromViewDataDictionary class and accessibleusing strings as keys.
 ViewBag is a dynamic property that takes advantageof 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’trequire typecasting for complex data type.
TempData:
TempData is a dictionary derived fromTempDataDictionary class and stored in shortlives session.It is a string key and object value.
Itkeep the information for the time of an HTTP Request. This mean only fromone page to another. Helps to maintain data when we
move fromone controller to other controller or from one action to other action. In other words when weredirect, “Tempdata” helps
to maintain data between those redirects. Itinternally uses session variables. Temp data useduring the currentand subsequent
request only means it is use when we are surethat next request will be redirecting to next view. Itrequires 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,
[HttpPost]
public ActionResult Edit(int? id, User userDetails)
{
TempData["TempData Name"] = "Akhil";
…..
And when View redirected to Index Action,
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 justone/two line of code.
Go to the Model class User.cs, add [Required(ErrorMessage = "FirstName is required")] on the top of FirstName property as,
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, weget,
Surprised!, Yes model validates itself with these annotations, there are many more validators like required field one that I used.
Do not forgetto include using System.ComponentModel.DataAnnotations; Namespace, when using Model Validation.This is the namespacethat
holds classes used for validation.
Conclusion:
Now we know whatMVC is ,how to Implement it,its advantages,CRUD operations in MVC.Upcoming parts of the
tutorial will be focussing on more advanced topics like EntityFramework, Repository Pattern,UnitOf Work Pattern.CodeFirstApproach.
Happy Coding .

More Related Content

What's hot

10 ways to bind multiple models on a view in mvc code project
10 ways to bind multiple models on a view in mvc   code project10 ways to bind multiple models on a view in mvc   code project
10 ways to bind multiple models on a view in mvc code project
Akshat Kumar
 
Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 
VIPER Architecture
VIPER ArchitectureVIPER Architecture
VIPER Architecture
Ahmed Lotfy
 
Cis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry universityCis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry university
lhkslkdh89009
 
Part 1 implementing a simple_web_service
Part 1 implementing a simple_web_servicePart 1 implementing a simple_web_service
Part 1 implementing a simple_web_service
krishmdkk
 

What's hot (20)

Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
 
10 ways to bind multiple models on a view in mvc code project
10 ways to bind multiple models on a view in mvc   code project10 ways to bind multiple models on a view in mvc   code project
10 ways to bind multiple models on a view in mvc code project
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
Struts notes
Struts notesStruts notes
Struts notes
 
Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
 
Adding a view
Adding a viewAdding a view
Adding a view
 
MVC 4
MVC 4MVC 4
MVC 4
 
VIPER Architecture
VIPER ArchitectureVIPER Architecture
VIPER Architecture
 
Cis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry universityCis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry university
 
Part 1 implementing a simple_web_service
Part 1 implementing a simple_web_servicePart 1 implementing a simple_web_service
Part 1 implementing a simple_web_service
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
 
Point and Click App Building Workshop
Point and Click App Building WorkshopPoint and Click App Building Workshop
Point and Click App Building Workshop
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
 
Adding User Management to Node.js
Adding User Management to Node.jsAdding User Management to Node.js
Adding User Management to Node.js
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Asp dot-net core problems and fixes
Asp dot-net core problems and fixes Asp dot-net core problems and fixes
Asp dot-net core problems and fixes
 
iOS Contact List Application Tutorial
iOS Contact List Application TutorialiOS Contact List Application Tutorial
iOS Contact List Application Tutorial
 
Advanced java lab swing mvc awt
Advanced java lab swing mvc awtAdvanced java lab swing mvc awt
Advanced java lab swing mvc awt
 

Viewers also liked

Ling to SQL and Entity Framework performance analysis
Ling to SQL and Entity Framework performance analysisLing to SQL and Entity Framework performance analysis
Ling to SQL and Entity Framework performance analysis
Alexander Konduforov
 
3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC
Mohd Manzoor Ahmed
 

Viewers also liked (18)

ASP.NET MVC: new era?
ASP.NET MVC: new era?ASP.NET MVC: new era?
ASP.NET MVC: new era?
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity Framework
 
Parallel Extentions to the .NET Framework
Parallel Extentions to the .NET FrameworkParallel Extentions to the .NET Framework
Parallel Extentions to the .NET Framework
 
Real-time ASP.NET with SignalR
Real-time ASP.NET with SignalRReal-time ASP.NET with SignalR
Real-time ASP.NET with SignalR
 
ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4
 
Ling to SQL and Entity Framework performance analysis
Ling to SQL and Entity Framework performance analysisLing to SQL and Entity Framework performance analysis
Ling to SQL and Entity Framework performance analysis
 
Building a MVC eCommerce Site in Under 5 Minutes
Building a MVC eCommerce Site in Under 5 MinutesBuilding a MVC eCommerce Site in Under 5 Minutes
Building a MVC eCommerce Site in Under 5 Minutes
 
Introducing LINQ
Introducing LINQIntroducing LINQ
Introducing LINQ
 
.NET,ASP .NET, Angular Js,LinQ
.NET,ASP .NET, Angular Js,LinQ.NET,ASP .NET, Angular Js,LinQ
.NET,ASP .NET, Angular Js,LinQ
 
Entity framework and how to use it
Entity framework and how to use itEntity framework and how to use it
Entity framework and how to use it
 
Dotnet Frameworks Version History
Dotnet Frameworks Version HistoryDotnet Frameworks Version History
Dotnet Frameworks Version History
 
Introduccion a LINQ
Introduccion a LINQIntroduccion a LINQ
Introduccion a LINQ
 
LINQ
LINQLINQ
LINQ
 
Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC
 
Introducing Entity Framework 4.0
Introducing Entity Framework 4.0Introducing Entity Framework 4.0
Introducing Entity Framework 4.0
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performance
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net framework
 

Similar to LearningMVCWithLINQToSQL

Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4
Akhil Mittal
 

Similar to LearningMVCWithLINQToSQL (20)

Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
ASP.NET Identity
ASP.NET IdentityASP.NET Identity
ASP.NET Identity
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4
 
Building richwebapplicationsusingasp
Building richwebapplicationsusingaspBuilding richwebapplicationsusingasp
Building richwebapplicationsusingasp
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senja
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101
 
Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)
 
CodeIgniter 101 Tutorial
CodeIgniter 101 TutorialCodeIgniter 101 Tutorial
CodeIgniter 101 Tutorial
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 
Mvc summary
Mvc summaryMvc summary
Mvc summary
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
MVC
MVCMVC
MVC
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
 
Volley lab btc_bbit
Volley lab btc_bbitVolley lab btc_bbit
Volley lab btc_bbit
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
 
MVC Training Part 2
MVC Training Part 2MVC Training Part 2
MVC Training Part 2
 

More from Akhil Mittal

Diving into VS 2015 Day5
Diving into VS 2015 Day5Diving into VS 2015 Day5
Diving into VS 2015 Day5
Akhil Mittal
 
Diving into VS 2015 Day4
Diving into VS 2015 Day4Diving into VS 2015 Day4
Diving into VS 2015 Day4
Akhil Mittal
 
Diving into VS 2015 Day3
Diving into VS 2015 Day3Diving into VS 2015 Day3
Diving into VS 2015 Day3
Akhil Mittal
 
Diving into VS 2015 Day2
Diving into VS 2015 Day2Diving into VS 2015 Day2
Diving into VS 2015 Day2
Akhil Mittal
 
Diving into VS 2015 Day1
Diving into VS 2015 Day1Diving into VS 2015 Day1
Diving into VS 2015 Day1
Akhil Mittal
 
Agile Release Planning
Agile Release PlanningAgile Release Planning
Agile Release Planning
Akhil Mittal
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 

More from Akhil Mittal (20)

PDFArticle
PDFArticlePDFArticle
PDFArticle
 
Diving into VS 2015 Day5
Diving into VS 2015 Day5Diving into VS 2015 Day5
Diving into VS 2015 Day5
 
Diving into VS 2015 Day4
Diving into VS 2015 Day4Diving into VS 2015 Day4
Diving into VS 2015 Day4
 
Diving into VS 2015 Day3
Diving into VS 2015 Day3Diving into VS 2015 Day3
Diving into VS 2015 Day3
 
Diving into VS 2015 Day2
Diving into VS 2015 Day2Diving into VS 2015 Day2
Diving into VS 2015 Day2
 
Diving into VS 2015 Day1
Diving into VS 2015 Day1Diving into VS 2015 Day1
Diving into VS 2015 Day1
 
Agile Release Planning
Agile Release PlanningAgile Release Planning
Agile Release Planning
 
RESTfulDay9
RESTfulDay9RESTfulDay9
RESTfulDay9
 
PDF_Article
PDF_ArticlePDF_Article
PDF_Article
 
RESTful Day 7
RESTful Day 7RESTful Day 7
RESTful Day 7
 
RESTful Day 6
RESTful Day 6RESTful Day 6
RESTful Day 6
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
 
IntroductionToMVC
IntroductionToMVCIntroductionToMVC
IntroductionToMVC
 
RESTful Day 5
RESTful Day 5RESTful Day 5
RESTful Day 5
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
Asp.net interview questions
Asp.net interview questionsAsp.net interview questions
Asp.net interview questions
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
 
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsCustom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
 
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
 
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
 

LearningMVCWithLINQToSQL

  • 1. Learning MVC-Part 2 Creating MVC Application& Perform CRUD operationsusing LINQ to SQL Introduction: In firstpart of the tutorial series we got a glimpse of MVC. In this partwe’ll focus on practical implementation of MVC Pattern. I don’tneed to explain about theory of MVC as we have already covered this in previous partof the article. Our Roadmap: We stick our agenda as follows, Part1: Introduction to MVC architecture and Separation of Concerns. Part 2: Creating MVC Application from scratch and connecting it with databaseusing LINQ to SQL. Part 3: Connecting the MVC Application with the help of EntityFramework DB-Firstapproach. Part 4: Connecting the MVC Application with the help of EntityFramework Code-Firstapproach. Part 5: Implementing Repository Pattern in MVC Application with EntityFramework. Part 6: Implementing a generic Repository Pattern and Unit Of Work pattern in MVCApplication with EntityFramework. Topics to be covered: 1. Creating MVC projectfromscratch. 2. Adding Controllers, Views and Models. 3. Creating sample databaseand use LINQ to SQL for communication. 4. PerformCRUD operations in MVC application using LINQ to SQL. 5. Understand ViewData, ViewBag and TempData. 6. Model Validation by System.Component.DataAnnotation.
  • 2. 1. Creating MVC project: Step1: Open VisualStudio 2010/2013,I amusing 2010.Goto File=>New=>Projectand select ASP.Net MVC3 Web Application, as shown below,
  • 3. Name the application as LearningMVC. Step2: A projecttemplate selection window will be opened, select Empty in that.Select View Engine as Razor and press OK.
  • 4. Step3: Now our solution is ready with an empty MVC application,
  • 5. We can clearly see that the solution contains some extra folders in comparison to traditional Asp.Net web application. We got Models, Views and Controllers folder and a Shared folder in Views folder. The folders as name denotes are used to hold the respective MVCplayers model-view-controllers, theshared folder in Views contains the _Layout.cshtml, that can be used as the master page for the views which we create. We see the global.asaxfile that contains a default routing table, that defines the route to be followed when request comes, it says that when request comes to Home controller, the Indexaction of that Home Controller has to be called,
  • 6. Actions are the methods defined in Controllers, that can be called defining a route, the Action methods can also contain parameters, in above mentioned figure, it says that Home controller has an Action Indexwhich contains an optional parameter id. When we run our application, we get something as shown below,
  • 7. Itsayethat the resourcewhich weare looking for can not be found.Therequestby default follows the default route as mentioned in global.asax, i.e. go to controller Home and invokemethod Index.Sincewe don’thave any of these yet, the browser shows this error. Never mind, lets make the browser happy. 2. Adding Controllers ,View and Models: Step1: Create a My Controller by right clicking on Controllers folder and add a controller named My, add the controller with empty read/write actions, it will give us a class with few default generated actions.
  • 8. Note that there are two Actions for every Action name, one is for Get i.e. when view loads for firsttime, and second one is for POST, when View is submitted with some data. Change global.asaxRegisterRoutes method as,
  • 9. public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "My", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } Note: we havechanged the name of controller as per our added controller. Step2: 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.Rightclick on Model folder add a class named User,
  • 10. Add following properties to User class,
  • 11. Now our model is created and we can create Views bound to this particular model. Step3: 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,
  • 12. Select Viewname as Details,Model class as User, and Scaffold Template as Details.This template specifies the role of the View, that this view will show the details of the User(entity).Click add. Likewiseperformthis operation for all the Actions, and create Views. Note that Views are automatically added, to Views folder under My folder(auto created as per Controller’s name).This is to maintain a particular structurefor MVC, so that we don’thave to take overhead to maintain it.
  • 13.
  • 14.
  • 15.
  • 16. Now we have controller as well as Views, so if we run the application we get,
  • 17. i.e. IndexAction of our My controller is Fired that returned IndexView. 3. Creating sample database and use LINQ to SQL for communication. Our MVC application is ready but, rather than displaying dummy data, I would go for running the application talking to a data base so that wecan cover wider aspect of the application. Step1: Create a database, script is given in the attachment, justexecute it over Sql Server 2005/2008. Step2: Add new Itemto the solution, and select LINQ to SQL class, call it MyDB.dbml
  • 19. Step3:Open Server explorer of Visual Studio, Open a connection, by providing Server name and existing databasename in Server Explorer Open Connection window,
  • 20.
  • 21. Click OK.Our solution looks like, Step4: Drag the User table to dbml designer window,wegetthe table in class diagram formatin designer window,
  • 22. When we open MyDB.designer.cs, weget MyDBDataContext class.This class holds databseUser table information in the formof Class and Properties.For every column of the table, properties are created in the class, and we can usethese properties to get/set values from/in database. 4. Perform CRUD operations in MVC application using LINQ to SQL.
  • 23. We now have a database, a context class to talk to data base and a MVC application to performCRUD operations in databaseusing the context class. Step1 Read: i) Go to IndexAction, makean instance of context class, Wecan get all the table and column names in that context’s instance. ii) Make a query to display all the records on Indexview. iii) Populate the User Model that we created earlier, and pass it to the Indexview(IndexView will be of List type Itemtemplate)
  • 24.
  • 25. When we run the application, weget empty list, i.e. we don’t haverecords in database,
  • 26. Step2 Create: i)Firstwritecode for creating a user, for the firsttime for Get Action of create, always an empty view will be returned.
  • 27. ii)When we postsome data on click of submitof Create, then we need to make a data entry in table for creating a new user. iii)When formposted, it fires PostAction 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 submitto data base.
  • 28. iv)Redirect action to Index, and now a record will be shown on the IndexView.We successfully created a user .
  • 31. Now we are smartenough to performupdate and delete by ourself, this I leave for reader’s understanding capabilities, below are the screens for Update and Delete. Edit Code: Get:
  • 34. Update reflected in database:
  • 35. Code to show details of a particular user :
  • 37. Note : Details Action do not have POSTone, as nothing to post to controller. Likewisefor Delete: Screen:
  • 38. Back to List after Delete: In databaseafter delete:
  • 39. Yes, all the CRUD operations done.Now we know MVC.
  • 40. There are few basic scenarios that I want to discuss beforefinishing with the First Part, like passing data fromController 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 regarding these three players. MVC provides us ViewData, VieBag and TempData for passing data fromcontroller, view and in next requests as well. ViewData and ViewBag are similar to someextent but TempData performs additional roles. Lets get key points on these three players: ViewBag & ViewData: I have written sampletest code in the sameapplication which we are following from the beginning, - Populate ViewData and ViewBag on Indexaction of My Controller,
  • 41. - Code in View to fetch ViewData/ViewBag,
  • 42. - When run the application, we get on screen,
  • 43. Following are roles and similarities between ViewData and ViewBag:  Maintains data when movefrom controller to view.  Passes data from controller to respectiveview.  Their value becomes null when any redirection occurs , becausetheir role is to providea way to communicate between controllers and views. It’s a communication mechanismwithin the server call. Differences between ViewData and ViewBag (taken from a blog):  ViewData is a dictionary of objects that is derived fromViewDataDictionary class and accessibleusing strings as keys.  ViewBag is a dynamic property that takes advantageof 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’trequire typecasting for complex data type. TempData: TempData is a dictionary derived fromTempDataDictionary class and stored in shortlives session.It is a string key and object value. Itkeep the information for the time of an HTTP Request. This mean only fromone page to another. Helps to maintain data when we move fromone controller to other controller or from one action to other action. In other words when weredirect, “Tempdata” helps to maintain data between those redirects. Itinternally uses session variables. Temp data useduring the currentand subsequent
  • 44. request only means it is use when we are surethat next request will be redirecting to next view. Itrequires 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, [HttpPost] public ActionResult Edit(int? id, User userDetails) { TempData["TempData Name"] = "Akhil"; ….. And when View redirected to Index Action,
  • 45. 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 justone/two line of code. Go to the Model class User.cs, add [Required(ErrorMessage = "FirstName is required")] on the top of FirstName property as, public int UserId { get; set; } [Required(ErrorMessage = "FirstName is required")] public string FirstName { get; set; } public string LastName { get; set; } ………..
  • 46. Now when we run the application, and try to Edit/Create user without specifying FirstName, weget, Surprised!, Yes model validates itself with these annotations, there are many more validators like required field one that I used. Do not forgetto include using System.ComponentModel.DataAnnotations; Namespace, when using Model Validation.This is the namespacethat holds classes used for validation. Conclusion: Now we know whatMVC is ,how to Implement it,its advantages,CRUD operations in MVC.Upcoming parts of the tutorial will be focussing on more advanced topics like EntityFramework, Repository Pattern,UnitOf Work Pattern.CodeFirstApproach. Happy Coding .