Learning MVC-Part 2 :Creating MVC Application & Perform CRUD operations using LINQ to SQL


Introduction:
                           In first part of the tutorial series we got a glimpse of MVC. In this part we’ll focus on practical implementation of MVC Pattern. I don’t 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 follows,
 
Topics to be covered:
1.     Creating 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:
     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 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 MVC players model-view-controllers, the shared 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.asax file 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 Index action 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 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 for can not be found.The request by default follows the default route as mentioned in global.asax, i.e. go to controller Home and invoke method Index.Since we don’t 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 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 first time, and second one is for POST, when View is submitted with some data.
Change global.asax RegisterRoutes method as,
  public static void RegisterRoutes(RouteCollectionroutes)
        {
            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 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 for them.But before this we’ll create a Model named User for our Views.Right click 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.
Likewise perform this 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 structure for MVC, so that we don’t 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 for 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 format in designer window,
 
When we open MyDB.designer.cs, we get MyDBDataContext class.This class holds databse 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 data base and a MVC application to perform 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 context’s 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 don’t have records in database,
 
Step2 Create:
i)First write code for creating a user, for the first time for 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 for creating a new user.
iii)When form posted, it fires 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 data base.
 
 
 iv)Redirect action to Index, and now a record will be shown on the Index View.We successfully created a user J.
 

v) In database :

Step3 Update & Step4 Delete:
Now we are smart enough to perform update 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 POST one, as nothing to post to controller.
Likewise for Delete:
 
Screen:
Back to List after Delete:
 
 
In database after delete:
 
Yes, all the CRUD operations done.Now we know MVC.
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  regarding these three players.
MVC provides us ViewData, VieBag 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. Lets 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,
         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 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:
 
TempData is a dictionary derived from 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 mean only from one page to another. Helps to maintain data when we move from one controller to other 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,
[HttpPost]
        public ActionResultEdit(int? id, UseruserDetails)
        {
            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 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 stringFirstName { get; set; }
        public stringLastName { get; set; }
………..
 
Now when we run the application, and try to Edit/Create user without specifying FirstName, we get,
 
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 usingSystem.ComponentModel.DataAnnotations; Namespace, when using Model Validation.This is the namespace that holds classes used for 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 focussing on more advanced topics like EntityFramework, Repository Pattern,Unit Of Work Pattern.Code First Approach.

 

Happy Coding J.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.

Advertisements

Learning MVC-Part 1 : Introduction to MVC Architecture and Separation of Concerns


Introduction:
 
After having gone through numerous of blogs and articles, I came to a conclusion that very few of the genuine writers have explained the topic from basics to its details in a full-fledged way with a working application. My effort in this MVC articles series would be to cover almost all the aspects of MVC starting from creating simple app and connecting with the database with various Microsoft providers. We’ll be gradually moving forward part by part to understand and practically implement all the scenarios.
Road Map:
All set, now we can start our journey with Part1.
Part1: Introduction to MVC architecture and Separation of Concerns.
Topics to be covered:
  • 1.     What does MVC mean.
  • 2.     Understand MVC Architecture.
  • 3.     Separation of Concerns

 

Players:
Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.
View: The user interface that renders the model into a form of interaction.
Controller: Handles a request from a view and updates the model that results a change in Model’s state.
To implement MVC in .NET we need mainly three classes (View, Controller and the Model).
MVC Architecture:
           The choice of MVC comes when we go for a solution where separation of concerns, ease of maintainability and extensibility of an application matters a lot. As per the architecture given below, we can see the request-response flow of a MVC application.

The architecture is self explanatory in itself. Browser as usual sends a request to IIS,IIS searches for the route defined in MVC application and passes request to the controller as per route, the controller communicates with model and passes the populated model(entity) to View(front end), Views are populated with model properties, and are rendered on the browser, passing the response to browser through IIS via controllers which invoked the particular View.

Separation of Concern:
As per Wikipedia ‘the process of breaking a computer program into distinct features that overlap in functionality as little as possible’. MVC design pattern aims to separate content from presentation and data-processing from content. Theoretically well, but where do we see this in MVC? One is reasonably clear – between the data-processing (Model) and the rest of the application.
When we talk about Views and Controllers, their ownership itself explains separation.The views are just the presentation form of an application, it does not have to know specifically about the requests coming from controller. The Model is independent of View and Controllers, it only holds business entities that can be passed to any View by controller as per need of exposing them to end user.The controller in independent of Views and Models, its sole purpose is to handle requests and pass it on as per the routes defined and as per need of rendering views.Thus our business entities(model), business logic(controllers) and presentation logic(views) lie in logical/physical layers independent of each other.
Conclusion:
Now we know why and where to use MVC, in another part of learning MVC we’ll be creating a MVC application from scratch, exploring the practical implementation of MVC.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.

 

Javascript Alert in C#


Code:

/// 

/// A JavaScript alert 

/// 

public static class Alert

{

    /// 

    /// Shows a client-side JavaScript alert in the browser.
    /// 


    /// The message to appear in the alert.

    public static void Show(string message)

    {

        // Cleans the message to allow single quotation marks

        string cleanMessage = message.Replace(“‘”“\\'”);
        string script = string.Format(“$(document).ready(function(){alert(‘{0}’);});”, cleanMessage);

        
// Gets the executing web page

        Page page = HttpContext.Current.CurrentHandler as Page;

        
// Checks if the handler is a Page and that the script isn’t all ready on the Page

        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered(“alert”))

        {

            page.ClientScript.RegisterClientScriptBlock(typeof(Alert), “alert”, script);

        }

    }

}

Session Helper Class (Facade)


                                                         
Code:
 using System.Web;
///

/// Static Session facade class
///

public static class SessionHelper
{
# region Private Constants
private const string userId = “UserId”;
private const string projectId = “ProjectId”;
# endregion
#region Private Static Member Variables
private static HttpContext thisContext;
#endregion
#region Public Static Methods
///

/// Clears Session
///

public static void ClearSession()
{
HttpContext.Current.Session.Clear();
}
///

/// Abandons Session
///

public static void Abandon()
{
ClearSession();
HttpContext.Current.Session.Abandon();
}
#endregion
#region Public Static Properties
///

/// Gets/Sets Session for UserId
///

public static string UserId
{
get
{
if (HttpContext.Current.Session[userId] == null)
return “”;
else
return HttpContext.Current.Session[userId].ToString();
}
set { HttpContext.Current.Session[userId] = value; }
}
public static string ProjectId
{
get
{
if (HttpContext.Current.Session[projectId] == null)
return “”;
else
return HttpContext.Current.Session[projectId].ToString();
}
set { HttpContext.Current.Session[projectId] = value; }
}
#endregion
}
//Use as: SessionHelper.UserId=”user1″;
//        string user=SessionHelper.UserId;
//        SessionHelper.Abandon();

Use the ENUM object to manipulate Enumerated Values


Enums are a tremendously easy way to make your code understandable. In the bad old days, when working on someone else’s program I’d be forced to decode code like this:
Dim cust As New Customer
cust.Type = 0
With an Enum, everything is more obvious:
Dim cust As New Customer
cust.Type = CustomerTypes.Deadbeat
What takes Enums to the next level are the static methods built into the Enum class. For instance, if I want to turn an Enum into an array of strings, I can use the Enum class’s GetNames method:
Dim cTypes As String() = [Enum].GetNames(GetType(CustomerTypes))
Because of the way Visual Basic handles names, Enum has to be enclosed in brackets to prevent syntax errors. C# doesn’t require those brackets:
string[] cTypes = Enum.GetNames(typeof(CustomerTypes));
I can then bind the output from GetNames to any listing control to get a list of the names in the Enum displayed in my user interface:
MyListBox.ItemsSource = Enum.GetNames(typeof(CustomerTypes));
GetNames shows the basic structure of the Enum class’s static methods: the first parameter to any method is always the Type of the Enum you want to work with. For instance, if you have code in a Web Service that’s passed the value of an Enum, you can convert that value into the name of the corresponding Enum entry using the Enum class’s GetName method. As before, the first parameter is the type of the Enum; the second parameter is the value you’re looking up:
Dim inputValue As Integer = 1
Me.MyTextBox.Text = [Enum].GetName(GetType(CustomerTypes), inputValue)
Parse goes one better and converts a string containing one of the names in an Enum into the Enum item itself. This code, for instance, sets the Customer object’s Type property to the appropriate Enum item based on a string value:
Dim custTypeString As String = "DeadBeat"
cust.Type = [Enum].Parse(
GetType(CustomerTypes), custTypeString);
Visual Basic doesn’t require the explicit cast to use Parse:
string custTypeString = "DeadBeat";
cust.Type = (CustomerTypes) Enum.Parse(
typeof(CustomerTypes), custTypeString);
If the string value you’re passing to Parse isn’t an item in the Enum, the Parse method throws an exception. To avoid that, you can use the Enum’s TryParse method which, while it still won’t do the conversion, won’t throw an exception either. An even better answer is to use the Enum’s IsDefined method to see if the item exists before trying to retrieve it:
if (Enum.IsDefined(typeof(CustomersType), custTypeString))
{
Customers ctype = (CustomersType) Enum.Parse(
typeof(CustomersType), custTypeString);
}
else
{
ErrorLabel.Text = "Not a valid customer type.";
}
(Taken from a blog.)

Features Added in Different Version of .Net Framework


.Net Framework 1.0 – This is the first version of .Net Framework that was released by Microsoft.

.Net Framework 1.1 – This is the 2nd major release of .Net Framework release by Microsoft. In this release it supports mobile ASP.Net controls, ODBC and Oracle Database. It also provides support for Internet Protocol version 6(I0v6).

.Net Framework 2.0 – It is part of Visual Studio 2005 and Microsoft SQL Server 2005. .Net Framework 2. Was the latest version of .Net Framework that has support Windows 2000.Net Framework 2.0 has many changes and enhancements as compared to ,Net Framework 1.1. It has a number of application programming interface changes. It contains many new personalization features for ASP.Net, for example, support for themes, skins, and web parts.

.Net Framework 3.0 – It uses the CLR version of 2.0. It contains a set of managed code APIs that form an integral part of Windows Vista and Windows Server 2008. .Net Framework 3.0 uses the same version of CLR that was incorporated with .Net Framework 2.0. It includes some new features as follows:
  1. Windows Presentation Foundation
  2. Windows Communication Foundation
  3. Windows Workflow Foundation
  4. Windows CardSpace
·.Net Framework 3.5 – .Net Framework 3.5 also uses the CLR version 2.0. In this release it supports LINQ, extension methods, lambda expression, anonymous types and built in Ajax support.

·.Net Framework 4.0 – In this release it supports PLINQ and Task Parallel Library. It supports Code Contracts and provides new types to work with arbitrary-precision arithmetic.