Introduction To MVC

In this article you will interact with thefollowing things:

  1. Introduction to MVC
  2. Sample program - Friend

What is MVC

MVC = Model View Controller

Model: Model define fields of view. There are two types of Model.

  1. Model (Entity): Directly interacted with table structure.
  2. ViewModel: Specially created for displaying the data that is VIEW.

View: Its visual representation of a model for Input and View activities.

Controller: Junction point of Model and View. The link between the view and model. It receive the request and take care of response. The deciding on which action execute.

In this article, we have used Visual Studio 2012.

  1. Create a new MVC 4 Project.

    Create a New MVC 4 Project

  2. Select a Template: Basic

    Select a Template

  3. Default folder structure of MVC 4 Basic application.

    MVC 4 Basic application

  4. By default following directory/folder are created.

    1. App_Data
    2. App_Start
    3. Content
    4. Controllers
    5. Models
    6. Scripts
    7. Views

  5. Create the following table in your database,
    1. SET ANSI_NULLS ON  
    2. GO  
    3. SET QUOTED_IDENTIFIER ON  
    4. GO  
    5. SET ANSI_PADDING ON  
    6. GO  
    7. CREATE TABLE [dbo].[tblFriends](  
    8.     [FriendID] [int] IDENTITY(1,1) NOT NULL,  
    9.     [FriendName] [varchar](50) NULL,  
    10.     [Place] [varchar](25) NULL,  
    11.             [Mobile] [varchar](15) NULL,  
    12.     [EmailAddress] [varchar](150) NULL  
    13. ON [PRIMARY]  
    14.   
    15. GO  
    16. SET ANSI_PADDING OFF  
    Add connection string inside WEB.CONFIG
    1. <connectionStrings>  
    2.    <add name="MemberCDACConnectionString" connectionString="Data Source=191.161.1.50\sa;Initial Catalog=MBKTest;User ID=sa;Password=server" providerName="System.Data.SqlClient"/>  
    3. </connectionStrings>  
    Model:

  6. Right click on MODELS and add class file named [FriendModel.cs]

    Class

    Note: Good practice to write suffix MODEL or VIEWMODEL after name.

    E.g. : FriendModel

Now we will discuss in detail about MODEL.

Data annotation Validation Attributes help to validate the model data in view while we submit the form. Data annotation attributes derived from using System.ComponentModel.DataAnnotations; this namespace.

DATA ANNOTATION ATTRIBUTE FOR MODEL DESCRIPTION
[KEY]

e.g.:

[Key]
public int FriendID { get; set; }
Primary key, this helpful even using EntityFramework CodeFirst also.
Here we just marked as primary key purpose. [This article we are using ADO.NET].
DisplayName

e.g.:

[Display(Name = "Friend Name")]
public string FriendName { get; set; }
To display title name for a property in view.
DataType

e.g.:

[DataType(DataType.Text)]
public string FriendName { get; set; }

[DataType(DataType.EmailAddress)]
public string EmailAddress { get; set; }
To define a datatype for a property.
Three are following type of datatype like:
Currency
Custom
Date
DateTime
Duration
EmailAddress
Html
ImageUrl
Multiline Text
Password
Phone Number
Text
Time
Url
Required

e.g.:

[Required(ErrorMessage="Friend Name Required") ]
public string FriendName { get; set; }

[Required(ErrorMessage="Place Required") ]
public string Place { get; set; }

[Required(ErrorMessage="Mobile Number Required") ]
public string Mobile { get; set; }

[Required(ErrorMessage="Email Address Required") ]
public string EmailAddress { get; set; }
To define mandatory / compulsory property to submit a (model) form to further process.
ErrorMessage : To display error message if this property blank.
MaxLength

e.g.:

[MaxLength(50, ErrorMessage = "Friend name not more than 50 characters")]
public string FriendName { get; set; }

[MaxLength(25, ErrorMessage = "Place name not more than 25 characters")]
public string Place { get; set; }

[MaxLength(15, ErrorMessage = "Mobile Number not more than 15 characters")]
public string Mobile { get; set; }

[MaxLength(150, ErrorMessage = "Email Address not more than 150 characters")]
public string EmailAddress { get; set; }
 

Model file code: FriendModel.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6. namespace MyFirstMvcApplication.Models  
  7. {  
  8.     public class FriendModel  
  9.     {  
  10.         [Key]  
  11.         [Display(Name = "Friend ID")]  
  12.         public int FriendID  
  13.         {  
  14.             get;  
  15.             set;  
  16.         }  
  17.         [Required(ErrorMessage = "Friend Name Required")]  
  18.         [Display(Name = "Friend Name")]  
  19.         [DataType(DataType.Text)]  
  20.         [MaxLength(50, ErrorMessage = "Friend name not more than 50 characters")]  
  21.         public string FriendName  
  22.         {  
  23.             get;  
  24.             set;  
  25.         }  
  26.         [Required(ErrorMessage = "Place Required")]  
  27.         [Display(Name = "Place")]  
  28.         [DataType(DataType.Text)]  
  29.         [MaxLength(25, ErrorMessage = "Place name not more than 25 characters")]  
  30.         public string Place  
  31.         {  
  32.             get;  
  33.             set;  
  34.         }  
  35.         [Required(ErrorMessage = "Mobile Number Required")]  
  36.         [Display(Name = "Mobile Number")]  
  37.         [DataType(DataType.Text)]  
  38.         [MaxLength(15, ErrorMessage = "Mobile Number not more than 15 characters")]  
  39.         public string Mobile  
  40.         {  
  41.             get;  
  42.             set;  
  43.         }  
  44.         [Required(ErrorMessage = "Email Address Required")]  
  45.         [Display(Name = "Email Address")]  
  46.         [DataType(DataType.EmailAddress)]  
  47.         [MaxLength(150, ErrorMessage = "Email Address not more than 150 characters")]  
  48.         public string EmailAddress  
  49.         {  
  50.             get;  
  51.             set;  
  52.         }  
  53.     }  
  54. }  
Repository

Right click on Project and create new folder named [REPOSITORY].

Now right click on [REPOSITORY] and add a new class file named [FRIENDREPOSITORY.CS].

Before going further, please build your project.

Under Repository we will create the following method which interact with DATABASE - from-to for data.

 

REPOSITORY METHOD DESCRIPTION
GetAllFriends Return data in IEnumerable format.
InsertNewFriend To create a new entry of friend.
GetFreindByFriendID To fetch a particular friend data by friend ID. Helpful for implement Update and Delete functionalities.
UpdateFriendByFriendID To update changes of friend data by Friend ID.
DeleteFriendByFriendID To delete a friend by friend ID.

Before starting coding in REPOSITORY, first we discuss about namespaces required to achieve functionalities.

Check System.Configuration in References folder, if its not there then first give reference of system.configuration.dll.

Namespace Required

Namespace Functionalities
Using System.Data To get ado.net data handling classes.
Using System.Data.SqlClient To connect to Microsoft Sql server.
Using Systen.Configuration To fetch configuration settings and connectionstrings from app.config.
Using MyFirstMvcApplication.Models To work with models inside repository, we have to give reference of folder.
MyFirstMvcApplication = This is our project name.

Controllers

Before going further, please build your project.

Create a new controller.

Add controller

By right click on CONTROLLER folder, click Add, Controller

CONTROLLER folder

Note: Here I had selected MVC Controller with empty read/write actions. 

By default in controller the following methods will be created:

CONTROLLER METHOD DESCRIPTION
Index Use for view of friends in list.
Details Use for view the particular friend detail.
Create Use for create a new friend.
Edit Use for edit/modify/change particular friend detail.
Delete Use for delete/erase particular friend.

In friend controller we have to pass namespace.

Namespace Required

Namespace Functionalities
Using MyFirstMvcApplication.Repository To access repository method in controller.
Using MyFirstMvcApplication.Models To work with models inside repository, we have to give reference of folder.
MyFirstMvcApplication = This is our project name.

And create instance of Friend Repository.

*Friend Repository

Now we are going step by step to implement the Methods of Repositories, Controllers and Views.

Repository:

GetAllFriends : To fetch all friends from the database.

  1. public IEnumerable < FriendModel > GetAllFriends()  
  2. {  
  3.     SqlConnection con = new SqlConnection(ConStr);  
  4.     SqlCommand cmd = new SqlCommand("Select * From tblFriends", con);  
  5.     con.Open();  
  6.     SqlDataReader reader = cmd.ExecuteReader();  
  7.     List < FriendModel > list = new List < FriendModel > ();  
  8.     while (reader.Read())  
  9.     {  
  10.         FriendModel _friend = new FriendModel();  
  11.         _friend.FriendID = Convert.ToInt16(reader["FriendID"]);  
  12.         _friend.FriendName = Convert.ToString(reader["FriendName"]);  
  13.         _friend.Mobile = Convert.ToString(reader["Mobile"]);  
  14.         _friend.Place = Convert.ToString(reader["Place"]);  
  15.         _friend.EmailAddress = Convert.ToString(reader["EmailAddress"]);  
  16.         list.Add(_friend);  
  17.     }  
  18.     IEnumerable < FriendModel > data = list;  
  19.     return data;  
  20. }  
Controller:

Index method implementation.
  1. public ActionResult Index()  
  2. {  
  3.    //Friend Repositry fetch records of friend.  
  4.    var dataList = _friendRepository.GetAllFriends();  
  5.   
  6.    return View(dataList);  
  7. }  
View:

Index view of friends list implementation.

Before going further, please build your project.

Right click on friend’s controller index method.

controller

Select Add View from above said menu.

Index view

Now here you can unde stand the above Add View dialogue box:

 

  1. View Name: Index
  2. View Engine: Razor
  3. Select Check Box: Create a strongly-typed view.
  4. Model Class: FriendModel
  5. Scaffold Template: List.

Scaffold Template: This is an option that what kind of view you want to create. By default scaffold template have the following options:

  • Create
  • Delete
  • Details
  • Edit
  • Empty
  • List

After pressing ADD button, inside VIEW folder FRIEND folder will be created because this view is part of FRIEND CONTROLLER. Inside the FRIEND folder this INDEX.CSHTML view will be created. 

View

Index.cshtml

  1. @model IEnumerable < MyFirstMvcApplication.Models.FriendModel > @  
  2. {  
  3.     ViewBag.Title = "Index";  
  4. } < h2 > Index < /h2>< p > @Html.ActionLink("Create New""Create") < /p>< table >< tr >< th > @Html.DisplayNameFor(model => model.FriendName) < /th>< th > @Html.DisplayNameFor(model => model.Place) < /th>< th > @Html.DisplayNameFor(model => model.Mobile) < /th>< th > @Html.DisplayNameFor(model => model.EmailAddress) < /th>< th >< /th>< /tr>  
  5. @foreach(var item in Model)  
  6. { < tr >< td > @Html.DisplayFor(modelItem => item.FriendName) < /td>< td > @Html.DisplayFor(modelItem => item.Place) < /td>< td > @Html.DisplayFor(modelItem => item.Mobile) < /td>< td > @Html.DisplayFor(modelItem => item.EmailAddress) < /td>< td > @Html.ActionLink("Edit""Edit"new  
  7.     {  
  8.         id = item.FriendID  
  9.     }) | @Html.ActionLink("Details""Details"new  
  10.     {  
  11.         id = item.FriendID  
  12.     }) | @Html.ActionLink("Delete""Delete"new  
  13.     {  
  14.         id = item.FriendID  
  15.     }) < /td>< /tr>  
  16. } < /table>  
Now press F5 to run application. On the web browser type,

http://localhost:????/friend/index

E.g.: http://localhost:1389/friend/index

run application

In above image you can see Email Address coming with mailto: and underline also because we have marked DataType as EmailAddress in Model.

GETALLFRIENDS implemented successfully. Above output should come.

Next Task is : INSERT A NEW FRIEND

INSERT FRIEND implementations in REPOSITORY, CONTROLLER and VIEW.

Repository

InsertNewFriend method code:
  1. /// <summary>  
  2. /// To insert a new friend.  
  3. /// </summary>  
  4. public void InsertNewFriend(FriendModel _friend)  
  5. {  
  6.     SqlConnection con = new SqlConnection(ConStr);  
  7.     con.Open();  
  8.     SqlCommand cmd = new SqlCommand("Insert into tblFriends (FriendName,FriendImage,Place,Mobile) Values(@FriendName,@FriendImage,@Place,@Mobile)", con);  
  9.     cmd.Parameters.AddWithValue("@FriendName", _friend.FriendName);  
  10.     cmd.Parameters.AddWithValue("@Place", _friend.Place);  
  11.     cmd.Parameters.AddWithValue("@Mobile", _friend.Mobile);  
  12.     cmd.Parameters.AddWithValue("@EmailAddress", _friend.EmailAddress);  
  13.     cmd.ExecuteNonQuery();  
  14. }  
Controller:

In friend controller you can see two methods named CREATE.

Submission kind of thing you should use two methods.

 

  1. HTTPGET: First load on browser.
  2. HTTPPOST: After submission of form.

I had marked manually [HttpGet] on the first method of CREATE, by default [HttpPost] comes on second method of CREATE.

Now right click on httpget method of create and click on add view same as we created a index view.

View

Now we will understand the above AddView dialogue box for CREATE.

  • View Name: Create
  • View Engine: Razor
  • Select Check Box: Create a strongly-typed view.
  • Model Class: FriendModel
  • Scaffold Template: Create.

After pressing ADD button, inside VIEW folder of FRIEND there is CREATE.CSHTML view will be created.

  1. //  
  2. // GET: /Friend/Create  
  3. [HttpGet]  
  4. public ActionResult Create()  
  5. {  
  6.    return View();  
  7. }  
Above code is created for HttpGet for Create method.

Now we create code of HttpPost for Create method.
  1. //  
  2. // POST: /Friend/Create  
  3. [HttpPost]  
  4. public ActionResult Create(FormCollection collection)  
  5. {  
  6.     try  
  7.     {  
  8.         // TODO: Add insert logic here  
  9.         return RedirectToAction("Index");  
  10.     }  
  11.     catch  
  12.     {  
  13.         return View();  
  14.     }  
  15. }  
You can use FormCollection also, better to use model. FormCollection means independent fields.

Above code is the default code which we had changed to this, because we are using model.
  1. //  
  2. // POST: /Friend/Create  
  3. [HttpPost]  
  4. public ActionResult Create(FriendModel _friendModelData)  
  5. {  
  6.     try  
  7.     {  
  8.         _friendRepository.InsertNewFriend(_friendModelData);  
  9.         return RedirectToAction("Index");  
  10.     }  
  11.     catch  
  12.     {  
  13.         return View();  
  14.     }  
  15. }  
In above code we are calling _friendRepository.InsertNewFriend and its a required FRIEND model to save the friend data.

Try Catch we had used because if new friend data store is successful, then we are calling INDEX view.

RedirectToAction: To redirect on other view.

View

Create.cshtml
  1. @model MyFirstMvcApplication.Models.FriendModel  
  2. @  
  3. {  
  4.     ViewBag.Title = "Create";  
  5. } < h2 > Create < /h2>  
  6. @using(Html.BeginForm())  
  7. {  
  8.     @Html.ValidationSummary(true) < fieldset >< legend > FriendModel < /legend>< div class = "editor-label" > @Html.LabelFor(model => model.FriendName) < /div>< div class = "editor-field" > @Html.EditorFor(model => model.FriendName)  
  9.     @Html.ValidationMessageFor(model => model.FriendName) < /div>< div class = "editor-label" > @Html.LabelFor(model => model.Place) < /div>< div class = "editor-field" > @Html.EditorFor(model => model.Place)  
  10.     @Html.ValidationMessageFor(model => model.Place) < /div>< div class = "editor-label" > @Html.LabelFor(model => model.Mobile) < /div>< div class = "editor-field" > @Html.EditorFor(model => model.Mobile)  
  11.     @Html.ValidationMessageFor(model => model.Mobile) < /div>< div class = "editor-label" > @Html.LabelFor(model => model.EmailAddress) < /div>< div class = "editor-field" > @Html.EditorFor(model => model.EmailAddress)  
  12.     @Html.ValidationMessageFor(model => model.EmailAddress) < /div>< p >< input type = "submit"  
  13.     value = "Create" / >< /p>< /fieldset>  
  14. } < div > @Html.ActionLink("Back to List""Index") < /div>  
  15. @section Scripts  
  16. {  
  17.     @Scripts.Render("~/bundles/jqueryval")  
  18. }  
Now press F5 to run application. On the web browser type,

http://localhost:????/friend/Index

Or you can change FRIEND Controller as your default startup controller.

To set your FRIEND controller as startup controller

Click on App_Start folder and double click on RouteConfig.cs file.

As you can see default controller is HOME and default action is INDEX.

Change to FRIEND and INDEX.

RouteConfig.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7. namespace MyFirstMvcApplication  
  8. {  
  9.     public class RouteConfig  
  10.     {  
  11.         public static void RegisterRoutes(RouteCollection routes)  
  12.         {  
  13.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  14.             routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new  
  15.             {  
  16.                 controller = "Friend", action = "Index", id = UrlParameter.Optional  
  17.             });  
  18.         }  
  19.     }  
  20. }  
Now you can see by default our FRIEND controller Index method executed, because of changes in ROUTECONFIG.cs file. 

You can click on Create New hyperlink to see CREATE view of FRIEND.

When CREATE view will executed it will display like the following,

CREATE view of FREIND

Now, click on Create button at the bottom. You see model validator executed with the help of JQuery.

Create button

Red colour is error message appearing on the screen because I had tried to submit blank form of friend. Error text coming from FREINDMODEL which we had mentioned.

Create

Fill the form and submit with Create button click.

submit

You can see new record add successfully.

INSERTNEWFRIENDS implemented successfully. Above output should come.

Next Task is : UPDATE

UPDATEFRIENDBY FRIENDID implementations in REPOSITORY, CONTROLLER and VIEW.

Repository

For updating existing friend data, first we have to fetch friend data then only we can change/mobile data on EDIT view.

To implement this first we have to create another method called GetFriendByFriendID which required FRIENDID to fetch the particular friend record.

GetFriendByFriendID code

  1. public FriendModel GetFriendByFriendID(int FriendID)  
  2. {  
  3.     SqlConnection con = new SqlConnection(ConStr);  
  4.     SqlCommand cmd = new SqlCommand("Select * From tblFriends where FriendID = " + FriendID, con);  
  5.     con.Open();  
  6.     SqlDataReader reader = cmd.ExecuteReader();  
  7.     FriendModel _friend = new FriendModel();  
  8.     _friend.FriendID = Convert.ToInt16(reader["FriendID"]);  
  9.     _friend.FriendName = Convert.ToString(reader["FriendName"]);  
  10.     _friend.Mobile = Convert.ToString(reader["Mobile"]);  
  11.     _friend.Place = Convert.ToString(reader["Place"]);  
  12.     _friend.EmailAddress = Convert.ToString(reader["EmailAddress"]);  
  13.     return _friend;  
  14. }  
UpdateFriendByFriendID code
  1. public void UpdateFriendByFriendID(FriendModel _friend)  
  2. {  
  3.     SqlConnection con = new SqlConnection(ConStr);  
  4.     con.Open();  
  5.     SqlCommand cmd = new SqlCommand("update tblFriends set FriendName =@FriendName ,Place = @Place ,Mobile = @Mobile ,EmailAddress= @EmailAddress where FriendID = " + _friend.FriendID, con);  
  6.     cmd.Parameters.AddWithValue("@FriendName", _friend.FriendName);  
  7.     cmd.Parameters.AddWithValue("@Place", _friend.Place);  
  8.     cmd.Parameters.AddWithValue("@Mobile", _friend.Mobile);  
  9.     cmd.Parameters.AddWithValue("@EmailAddress", _friend.EmailAddress);  
  10.     cmd.ExecuteNonQuery();  
  11. }  
Controller

In friend controller you can see two methods with name EDIT.

Its also having two methods HTTPGET and HTTPPOST.

Now right click on httpget method of create and click on add view same as we created a CREATE view.

CREATE view

Now we will understand the above AddView dialogue box for EDIT.

 

    f. View Name: Edit
    g. View Engine: Razor
    h. Select Check Box : Create a strongly-typed view.
    i. Model Class: FriendModel
    j. Scaffold Template: Edit.

After pressing ADD button, inside VIEW folder of FRIEND, EDIT.CSHTML view will be created. 

  1. [HttpGet]  
  2. public ActionResult Edit(int id)  
  3. {  
  4.     //above id value given to our friendrepository method to fetch selected friend data.  
  5.     var SelectedFriend = _friendRepository.GetFriendByFriendID(id);  
  6.     return View();  
  7. }  
  8. // POST: /Friend/Edit/5  
  9. [HttpPost]  
  10. public ActionResult Edit(FriendModel _friend)  
  11. {  
  12.     try  
  13.     {  
  14.         // _friend model given to friendrepository update method to udpate database.  
  15.         _friendRepository.UpdateFriendByFriendID(_friend);  
  16.         return RedirectToAction("Index");  
  17.     }  
  18.     catch  
  19.     {  
  20.         return View();  
  21.     }  
  22. }   
View

Edit.cshtml
  1. @model MyFirstMvcApplication.Models.FriendModel  
  2. @  
  3. {  
  4.     ViewBag.Title = "Edit";  
  5. } < h2 > Edit < /h2>  
  6. @using(Html.BeginForm())  
  7. {  
  8.     @Html.ValidationSummary(true) < fieldset > < legend > FriendModel < /legend>  
  9.     @Html.HiddenFor(model => model.FriendID) < div class = "editor-label" > @Html.LabelFor(model => model.FriendName) < /div> < div class = "editor-field" > @Html.EditorFor(model => model.FriendName)  
  10.     @Html.ValidationMessageFor(model => model.FriendName) < /div> < div class = "editor-label" > @Html.LabelFor(model => model.Place) < /div> < div class = "editor-field" > @Html.EditorFor(model => model.Place)  
  11.     @Html.ValidationMessageFor(model => model.Place) < /div> < div class = "editor-label" > @Html.LabelFor(model => model.Mobile) < /div> < div class = "editor-field" > @Html.EditorFor(model => model.Mobile)  
  12.     @Html.ValidationMessageFor(model => model.Mobile) < /div> < div class = "editor-label" > @Html.LabelFor(model => model.EmailAddress) < /div> < div class = "editor-field" > @Html.EditorFor(model => model.EmailAddress)  
  13.     @Html.ValidationMessageFor(model => model.EmailAddress) < /div> < p > < input type = "submit"  
  14.     value = "Save" / > < /p> < /fieldset>  
  15. } < div > @Html.ActionLink("Back to List""Index") < /div>  
  16. @section Scripts  
  17. {  
  18.     @Scripts.Render("~/bundles/jqueryval")  
  19. }  
Now press F5 to check and test our EDIT functionalities.

EDIT functionalities

When you mouse hover on last record EDIT link button

At bottom left side link will display like the following,

Localhost

It means when you click on marked blue underline 7th ID number of record will come for edit.

record

You can see all details of selected row data comes in edit screen.

Now, will change place Jodhpur to Bikaner.

Edit

After click on Save button, Index view will verify that our changes took place or not.

SAVE

You can see Bikaner place changed successfully.

Next Task is : DETAILS

DETAILFRIENDBY FREINDID implementations in REPOSITORY, CONTROLLER and VIEW

Repository

To see the detail of an existing friend data, first we have to fetch friend data then only we can display data on Detail view.

To implement Detail functionalities, first we have to reuse our existing method called GetFriendByFriendID to fetch the particular friend record.

Controller

In friend controller you can see method named Detail.

Its having only one method HTTPGET.

Now right click on detail method and select add view same as we did previously.

 select add view

Now we will understand the above AddView dialogue box for DETAILS.

 

  1. View Name: Details
  2. View Engine: Razor
  3. Select Check Box: Create a strongly-typed view.
  4. Model Class: FriendModel
  5. Scaffold Template: Details.

After pressing ADD button, inside VIEW folder of FRIEND, DETAILS.CSHTML view will be created.

  1. [HttpGet]  
  2. public ActionResult Details(int id)  
  3. {  
  4.    //above id value given to our friendrepository method to fetch selected friend data.  
  5.    var SelectedFriend = _friendRepository.GetFriendByFriendID(id);  
  6.    return View(SelectedFriend);  
  7. }  
View

Details.cshtml
  1. @model MyFirstMvcApplication.Models.FriendModel  
  2.   
  3. @{  
  4. ViewBag.Title = "Details";  
  5. }  
  6.   
  7.   
  8. <h2>Details</h2>  
  9. <fieldset>  
  10.     <legend>FriendModel</legend>  
  11.     <div class="display-label">  
  12. @Html.DisplayNameFor(model => model.FriendName)  
  13. </div>  
  14.     <div class="display-field">  
  15. @Html.DisplayFor(model => model.FriendName)  
  16. </div>  
  17.     <div class="display-label">  
  18. @Html.DisplayNameFor(model => model.Place)  
  19. </div>  
  20.     <div class="display-field">  
  21. @Html.DisplayFor(model => model.Place)  
  22. </div>  
  23.     <div class="display-label">  
  24. @Html.DisplayNameFor(model => model.Mobile)  
  25. </div>  
  26.     <div class="display-field">  
  27. @Html.DisplayFor(model => model.Mobile)  
  28. </div>  
  29.     <div class="display-label">  
  30. @Html.DisplayNameFor(model => model.EmailAddress)  
  31. </div>  
  32.     <div class="display-field">  
  33. @Html.DisplayFor(model => model.EmailAddress)  
  34. </div>  
  35. </fieldset>  
  36. <p>  
  37. @Html.ActionLink("Edit""Edit"new { id=Model.FriendID }) |  
  38. @Html.ActionLink("Back to List""Index")  
  39. </p>  
Now press F5 to check and test our DETAILS functionalities.

DETAILS functionalities

Now click Details marked blue colour underline.

DETAILS

In DETAILS view by default there is a link of Edit and Back to List.

Next Task is : DELETE

DELETEFRIENDBY FREINDID implementations in REPOSITORY, CONTROLLER and VIEW

Repository

To delete a specific/particular friend data, first we have to fetch friend data then take confirmation of delete on delete page.

Microsoft suggest delete data on HTTPPOST method not on HTTPGET

To implement Detail functionalities, first we have to reuse our existing method called GetFriendByFriendID to fetch the particular friend record.
  1. // <summary>  
  2. /// To delete a friend by friend id.  
  3. /// </summary>  
  4. /// <param name="_friend"></param>  
  5. public void DeleteFriendByFriendID(FriendModel _friend)  
  6. {  
  7.    SqlConnection con = new SqlConnection(ConStr);  
  8.    con.Open();  
  9.    SqlCommand cmd = new SqlCommand("Delete From tblFriends where FriendID = " + _friend.FriendID, con);  
  10.    cmd.ExecuteNonQuery();  
  11. }  
Controller

In friend controller you can see method named Delete.

Its having two delete method HTTPGET, HTTPPOST.

Now right click on delete method and select add view same as we did previously.

Add view

Now we will understand the above AddView dialogue box for DELETE.

 

  1. View Name: Delete
  2. View Engine: Razor
  3. Select Check Box: Create a strongly-typed view.
  4. Model Class: FriendModel
  5. Scaffold Template: Delete.

After press ingADD button, inside VIEW folder of FRIEND, the DELETE.CSHTML view will be created. 

  1. //  
  2. // GET: /Friend/Delete/5  
  3. [HttpGet]  
  4. public ActionResult Delete(int id)  
  5. {  
  6.     //above id value given to our friendrepository method to fetch selected friend data.  
  7.     var SelectedFriend = _friendRepository.GetFriendByFriendID(id);  
  8.     return View(SelectedFriend);  
  9. }  
  10. //  
  11. // POST: /Friend/Delete/5  
  12. [HttpPost]  
  13. public ActionResult Delete(FriendModel _friend)  
  14. {  
  15.     try  
  16.     {  
  17.         _friendRepository.DeleteFriendByFriendID(_friend);  
  18.         return RedirectToAction("Index");  
  19.     }  
  20.     catch  
  21.     {  
  22.         return View();  
  23.     }  
  24. }  
View

Delete.cshtml
  1. @model MyFirstMvcApplication.Models.FriendModel  
  2.   
  3. @{  
  4. ViewBag.Title = "Delete";  
  5. }  
  6.   
  7.   
  8. <h2>Delete</h2>  
  9. <h3>Are you sure you want to delete this?</h3>  
  10. <fieldset>  
  11.     <legend>FriendModel</legend>  
  12.     <div class="display-label">  
  13. @Html.DisplayNameFor(model => model.FriendName)  
  14. </div>  
  15.     <div class="display-field">  
  16. @Html.DisplayFor(model => model.FriendName)  
  17. </div>  
  18.     <div class="display-label">  
  19. @Html.DisplayNameFor(model => model.Place)  
  20. </div>  
  21.     <div class="display-field">  
  22. @Html.DisplayFor(model => model.Place)  
  23. </div>  
  24.     <div class="display-label">  
  25. @Html.DisplayNameFor(model => model.Mobile)  
  26. </div>  
  27.     <div class="display-field">  
  28. @Html.DisplayFor(model => model.Mobile)  
  29. </div>  
  30.     <div class="display-label">  
  31. @Html.DisplayNameFor(model => model.EmailAddress)  
  32. </div>  
  33.     <div class="display-field">  
  34. @Html.DisplayFor(model => model.EmailAddress)  
  35. </div>  
  36. </fieldset>  
  37. @using (Html.BeginForm()) {  
  38.   
  39. <p>  
  40.     <input type="submit" value="Delete" /> |  
  41. @Html.ActionLink("Back to List""Index")  
  42.   
  43. </p>  
  44. }  
Now press F5 to check and test our DELETE functionalities.

DELETE functionalities

Now click on Delete button marked with blue colour.

Delete

Last record selected for delete. As I click on Delete button, check Index view for delete functionalities result.

Index

Full Code

FriendController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MyFirstMvcApplication.Models;  
  7. using MyFirstMvcApplication.Repository;  
  8.   
  9. namespace MyFirstMvcApplication.Controllers {  
  10.  public class FriendController: Controller {  
  11.   
  12.   FriendRepository _friendRepository = new FriendRepository();  
  13.   
  14.   //  
  15.   // GET: /Friend/  
  16.   public ActionResult Index() {  
  17.    //Friend Repositry fetch records of friend.  
  18.    var dataList = _friendRepository.GetAllFriends();  
  19.   
  20.    return View(dataList);  
  21.   }  
  22.   
  23.   
  24.   //  
  25.   // GET: /Friend/Create  
  26.   [HttpGet]  
  27.   public ActionResult Create() {  
  28.    return View();  
  29.   }  
  30.   
  31.   //  
  32.   // POST: /Friend/Create  
  33.   
  34.   [HttpPost]  
  35.   public ActionResult Create(FriendModel _friendModelData) {  
  36.    try {  
  37.     _friendRepository.InsertNewFriend(_friendModelData);  
  38.     return RedirectToAction("Index");  
  39.    } catch {  
  40.     return View();  
  41.    }  
  42.   }  
  43.   
  44.   
  45.   
  46.   
  47.   //  
  48.   // GET: /Friend/Edit/5  
  49.   [HttpGet]  
  50.   public ActionResult Edit(int id) {  
  51.   
  52.    //above id vlaue given to our friendrepository method to fetch selected friend data.  
  53.    var SelectedFriend = _friendRepository.GetFriendByFriendID(id);  
  54.    return View(SelectedFriend);  
  55.   }  
  56.   
  57.   //  
  58.   // POST: /Friend/Edit/5  
  59.   
  60.   [HttpPost]  
  61.   public ActionResult Edit(FriendModel _friend) {  
  62.    try {  
  63.   
  64.     // _friend model given to friendrepository update method to udpate database.  
  65.     _friendRepository.UpdateFriendByFriendID(_friend);  
  66.     return RedirectToAction("Index");  
  67.    } catch {  
  68.     return View();  
  69.    }  
  70.   }  
  71.   
  72.   //  
  73.   // GET: /Friend/Details/5  
  74.   [HttpGet]  
  75.   public ActionResult Details(int id) {  
  76.    //above id value given to our friendrepository method to fetch selected friend data.  
  77.    var SelectedFriend = _friendRepository.GetFriendByFriendID(id);  
  78.    return View(SelectedFriend);  
  79.   }  
  80.   
  81.   
  82.   
  83.   //  
  84.   // GET: /Friend/Delete/5  
  85.   [HttpGet]  
  86.   public ActionResult Delete(int id) {  
  87.    //above id value given to our friendrepository method to fetch selected friend data.  
  88.    var SelectedFriend = _friendRepository.GetFriendByFriendID(id);  
  89.    return View(SelectedFriend);  
  90.   }  
  91.   
  92.   //  
  93.   // POST: /Friend/Delete/5  
  94.   
  95.   [HttpPost]  
  96.   [ActionName("Delete")]  
  97.   public ActionResult Delete2(int id) {  
  98.   
  99.    try {  
  100.     _friendRepository.DeleteFriendByFriendID(id);  
  101.     return RedirectToAction("Index");  
  102.    } catch {  
  103.     return View();  
  104.    }  
  105.   }  
  106.  }  
  107. }  
FriendRepository.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data;  
  6. using System.Data.SqlClient;  
  7. using MyFirstMvcApplication.Models;  
  8. using System.Configuration;  
  9. namespace MyFirstMvcApplication.Repository  
  10. {  
  11.     public class FriendRepository  
  12.     {  
  13.         string ConStr = ConfigurationManager.ConnectionStrings["MemberCDACConnectionString"].ConnectionString;  
  14.         /// <summary>  
  15.         /// To Generate a list of all friends  
  16.         /// </summary>  
  17.         public IEnumerable < FriendModel > GetAllFriends()  
  18.         {  
  19.             SqlConnection con = new SqlConnection(ConStr);  
  20.             SqlCommand cmd = new SqlCommand("Select * From tblFriends", con);  
  21.             con.Open();  
  22.             SqlDataReader reader = cmd.ExecuteReader();  
  23.             List < FriendModel > list = new List < FriendModel > ();  
  24.             while (reader.Read())  
  25.             {  
  26.                 FriendModel _friend = new FriendModel();  
  27.                 _friend.FriendID = Convert.ToInt16(reader["FriendID"]);  
  28.                 _friend.FriendName = Convert.ToString(reader["FriendName"]);  
  29.                 _friend.Mobile = Convert.ToString(reader["Mobile"]);  
  30.                 _friend.Place = Convert.ToString(reader["Place"]);  
  31.                 _friend.EmailAddress = Convert.ToString(reader["EmailAddress"]);  
  32.                 list.Add(_friend);  
  33.             }  
  34.             IEnumerable < FriendModel > data = list;  
  35.             return data;  
  36.         }  
  37.         /// <summary>  
  38.         /// To insert a new friend.  
  39.         /// </summary>  
  40.         public void InsertNewFriend(FriendModel _friend)  
  41.         {  
  42.             SqlConnection con = new SqlConnection(ConStr);  
  43.             con.Open();  
  44.             SqlCommand cmd = new SqlCommand("Insert into tblFriends (FriendName,Place,Mobile,EmailAddress) Values(@FriendName,@Place,@Mobile,@EmailAddress)", con);  
  45.             cmd.Parameters.AddWithValue("@FriendName", _friend.FriendName);  
  46.             cmd.Parameters.AddWithValue("@Place", _friend.Place);  
  47.             cmd.Parameters.AddWithValue("@Mobile", _friend.Mobile);  
  48.             cmd.Parameters.AddWithValue("@EmailAddress", _friend.EmailAddress);  
  49.             cmd.ExecuteNonQuery();  
  50.         }  
  51.         /// <summary>  
  52.         /// To fetch a particular friend data by friend ID.   
  53.         /// </summary>  
  54.         public FriendModel GetFriendByFriendID(int FriendID)  
  55.         {  
  56.             SqlConnection con = new SqlConnection(ConStr);  
  57.             SqlCommand cmd = new SqlCommand("Select * From tblFriends where FriendID = " + FriendID, con);  
  58.             con.Open();  
  59.             SqlDataReader reader = cmd.ExecuteReader();  
  60.             FriendModel _friend = new FriendModel();  
  61.             while (reader.Read())  
  62.             {  
  63.                 _friend.FriendID = Convert.ToInt16(reader["FriendID"]);  
  64.                 _friend.FriendName = Convert.ToString(reader["FriendName"]);  
  65.                 _friend.Mobile = Convert.ToString(reader["Mobile"]);  
  66.                 _friend.Place = Convert.ToString(reader["Place"]);  
  67.                     _friend.EmailAddress = Convert.ToString(reader["EmailAddress"]);  
  68.             }  
  69.             return _friend;  
  70.         }  
  71.         /// <summary>  
  72.         /// To update a friend by friend id.  
  73.         /// </summary>  
  74.         /// <param name="_friend"></param>  
  75.         public void UpdateFriendByFriendID(FriendModel _friend)  
  76.         {  
  77.             SqlConnection con = new SqlConnection(ConStr);  
  78.             con.Open();  
  79.             SqlCommand cmd = new SqlCommand("update tblFriends set FriendName =@FriendName ,Place = @Place ,Mobile = @Mobile ,EmailAddress= @EmailAddress where FriendID = " + _friend.FriendID, con);  
  80.             cmd.Parameters.AddWithValue("@FriendName", _friend.FriendName);  
  81.             cmd.Parameters.AddWithValue("@Place", _friend.Place);  
  82.             cmd.Parameters.AddWithValue("@Mobile", _friend.Mobile);  
  83.             cmd.Parameters.AddWithValue("@EmailAddress", _friend.EmailAddress);  
  84.             cmd.ExecuteNonQuery();  
  85.         }  
  86.         /// <summary>  
  87.         /// To delete a friend by friend id.  
  88.         /// </summary>  
  89.         /// <param name="_friend"></param>  
  90.         public void DeleteFriendByFriendID(int FriendID)  
  91.         {  
  92.             SqlConnection con = new SqlConnection(ConStr);  
  93.             con.Open();  
  94.             SqlCommand cmd = new SqlCommand("Delete From tblFriends where FriendID = " + FriendID, con);  
  95.             cmd.ExecuteNonQuery();  
  96.         }  
  97.     }  
  98. }  
We had achieved the following functionalities,

 

  1. List of Friends
  2. Insert a Friend
  3. Update a Friend
  4. Delete a Friend

If you have any doubt feel free to ask.

Up Next
    Ebook Download
    View all
    Learn
    View all