Vous êtes sur la page 1sur 27

csharppulse .blo gspo t .

in

http://csharppulse.blo gspo t.in/2013/08/learning-mvc-part-2-creating-mvc.html

Learning MVC-Part 2 :Creating MVC Application & Perform CRUD operations using LINQ to SQL
Download Complete Source Code Introduction: In f irst part of the tutorial series we got a glimpse of MVC. In this part well f ocus on practical implementation of MVC Pattern. I dont need to explain about theory of MVC as we have already covered this in previous part of the article. Our Roadmap: We stick our agenda as f ollows,

1. Part1: Introduction to MVCarchitecture and Separation of Concerns. 2. Part 2: Creating MVC Application fromscratch and connecting it with database using LINQ to SQL. 3. Part 3: Connecting the MVC Application with the help of EntityFramework DB-First approach. 4. Part 4: Connecting the MVC Application with the help of EntityFramework Code-First approach. 5. Part 5: Implementing Repository Pattern in MVC Application with EntityFramework. 6. Part 6: Implementing a generic Repository Pattern and Unit Of Work pattern in MVC Application with EntityFramework.

Topics to be covered: 1. 2. 3. 4. 5. 6. 1. Creating MVC project f rom scratch. Adding Controllers, Views and Models. Creating sample database and use LINQ to SQL f or communication. Perf orm CRUD operations in MVC application using LINQ to SQL. Understand ViewData, ViewBag and TempData. Model Validation by System.Component.DataAnnotation. Creating MVC project:

Step1: Open Visual Studio 2010/2013,I am using 2010.Goto File=>New=>Project and select ASP.Net MVC3 Web Application, as shown below,

Name the application as LearningMVC. Step2: A project template 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 f olders in comparison to traditional Asp.Net web application. We got Models, Views and Controllers f older and a Shared f older in Views f older. T he f olders as name denotes are used to hold the respective MVC players model-view-controllers, the shared f older in Views contains the _Layout.cshtml, that can be used as the master page f or the views which we create. We see the global.asax f ile that contains a def ault routing table, that def ines the route to be f ollowed when request comes, it says that when request comes to Home controller, the Index action of that Home Controller has to be called,

Actions are the methods def ined in Controllers, that can be called def ining a route, the Action methods can also contain parameters, in above mentioned f igure, it says that Home controller has an Action Index which contains an optional parameter id. When we run our application, we get something as shown below,

It says that the resource which we are looking f or can not be f ound.T he request by def ault f ollows the def ault route as mentioned in global.asax, i.e. go to controller Home and invoke method Index.Since we dont have 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 f older and add a controller named My, add the controller with empty read/write actions, it will give us a class with f ew def ault generated actions.

Note that there are two Actions f or every Action name, one is f or Get i.e. when view loads f or f irst time, and second one is f or POST, when View is submitted with some data. Change global.asax RegisterRoutes method as, public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInf o}"); routes.MapRoute( "Def ault", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "My", action = "Index", id = UrlParameter.Optional } // Parameter def aults ); } Note: we have changed 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 f or them.But bef ore this well create a Model named User f or our Views.Right click on Model f older add a class named User,

Add f ollowing 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 f rom the context menu select AddView on the top.By def ault the View name is same as of Actions name. e.g. For Details,

Select Viewname as Details,Model class as User, and Scaf f old Template as Details.T his template specif ies the role of the View, that this view will show the details of the User(entity).Click add. Likewise perf orm this operation f or all the Actions, and create Views. Note that Views are automatically added, to Views f older under My f older(auto created as per Controllers name).T his is to maintain a particular structure f or MVC, so that we dont have to take overhead to maintain it.

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

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

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 f or running the application talking to a data base so that we can cover wider aspect of the application. Step1: Create a database, script is given in the attachment, just execute it over Sql Server 2005/2008. Step2: Add new Item to 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 database name in Server Explorer Open Connection window,

Click OK.Our solution looks like,

Step4: Drag the User table to dbml designer window,we get the table in class diagram f ormat in designer window,

When we open MyDB.designer.cs, we get MyDBDataContext class.T his class holds databse User table inf ormation in the f orm 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 f rom/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 perf orm CRUD operations in database using the context class.

Step1 Read : i) Go to Index Action, make an instance of context class, We can get all the table and column names in that contexts instance. ii) Make a query to display all the records on Index view. iii) Populate the User Model that we created earlier, and pass it to the Index view(Index View will be of List type Item template)

When we run the application, we get empty list, i.e. we dont have records in database,

Step2 Create: i)First write code f or creating a user, f or the f irst time f or Get Action of create, always an empty view will be returned.

ii)When we post some data on click of submit of Create, then we need to make a data entry in table f or creating a new user. iii)When f orm posted, it f ires Post Action of Create with the already bound User model properties to view f ields, well retrieve these model properties and make an instance of context class populate context User and submit to data base.

iv)Redirect action to Index, and now a record will be shown on the Index View.We successf ully created a user J.

v) In database :

Step3 Update & Step4 Delete: Now we are smart enough to perf orm update and delete by ourself , this I leave f or readers understanding capabilities, below are the screens f or Update and Delete. Edit Code: Get:

Post:

Get Action View of Edit:

Edited f ew f ields:

Update ref lected in database:

Code to show details of a particular user :

Details Screen:

Note : Details Action do not have POST one, as nothing to post to controller. Likewise f or Delete: Screen:

Back to List af ter Delete:

In database af ter delete:

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

T here are f ew basic scenarios that I want to discuss bef ore f inishing with the First Part, like passing data f rom 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 conf usion regarding these three players.

MVC provides us ViewData, VieBag and TempData f or passing data f rom controller, view and in next requests as well. ViewData and ViewBag are similar to some extent but TempData perf orms additional roles. Lets get key points on these three players: ViewBag & ViewData : I have written sample test code in the same application which we are f ollowing f rom the beginning, Populate ViewData and ViewBag on Index action of My Controller,

Code in View to f etch ViewData/ViewBag,

When run the application, we get on screen,

Following are roles and similarities between ViewData and ViewBag: Maintains data when move f rom controller to view. Passes data f rom controller to respective view. T heir value becomes null when any redirection occurs , because their role is to provide a way to communicate between controllers and views. Its 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 f rom ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic f eatures in C# 4.0. ViewData requires typecasting f or complex data type and check f or null values to avoid error. ViewBag doesnt require typecasting f or complex data type. TempData: TempData is a dictionary derived f rom TempDataDictionary class and stored in short lives session.It is a string key and object value. It keep the inf ormation f or the time of an HT T P Request. T his mean only f rom one page to another. Helps to maintain data when we move f rom one controller to other controller or f rom 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 f or complex data type and check f or 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 f or implementing validation in our Web Application Client Side, Server Side etc But MVC provides us a f eature with which we can annotate our Model f or validation by writing just one/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 specif ying FirstName, we get,

Surprised!, Yes model validates itself with these annotations, there are many more validators like required f ield one that I used. Do not f orget to include using System.ComponentModel.DataAnnotations; Namespace, when using Model Validation.T his is the namespace that holds classes used f or validation.

Conclusion:

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

Vous aimerez peut-être aussi