In this article you will interact with thefollowing things:
- Introduction to MVC
- Sample program - Friend
What is MVC
MVC = Model View Controller
Model: Model define fields of view. There are two types of Model.
- Model (Entity): Directly interacted with table structure.
- 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.
- Create a new MVC 4 Project.
- Select a Template: Basic
- Default folder structure of MVC 4 Basic application.
- By default following directory/folder are created.
- App_Data
- App_Start
- Content
- Controllers
- Models
- Scripts
- Views
- Create the following table in your database,
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- SET ANSI_PADDING ON
- GO
- CREATE TABLE [dbo].[tblFriends](
- [FriendID] [int] IDENTITY(1,1) NOT NULL,
- [FriendName] [varchar](50) NULL,
- [Place] [varchar](25) NULL,
- [Mobile] [varchar](15) NULL,
- [EmailAddress] [varchar](150) NULL
- ) ON [PRIMARY]
-
- GO
- SET ANSI_PADDING OFF
Add connection string inside WEB.CONFIG
- <connectionStrings>
- <add name="MemberCDACConnectionString" connectionString="Data Source=191.161.1.50\sa;Initial Catalog=MBKTest;User ID=sa;Password=server" providerName="System.Data.SqlClient"/>
- </connectionStrings>
Model:
- Right click on MODELS and add class file named [FriendModel.cs]
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
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
- namespace MyFirstMvcApplication.Models
- {
- public class FriendModel
- {
- [Key]
- [Display(Name = "Friend ID")]
- public int FriendID
- {
- get;
- set;
- }
- [Required(ErrorMessage = "Friend Name Required")]
- [Display(Name = "Friend Name")]
- [DataType(DataType.Text)]
- [MaxLength(50, ErrorMessage = "Friend name not more than 50 characters")]
- public string FriendName
- {
- get;
- set;
- }
- [Required(ErrorMessage = "Place Required")]
- [Display(Name = "Place")]
- [DataType(DataType.Text)]
- [MaxLength(25, ErrorMessage = "Place name not more than 25 characters")]
- public string Place
- {
- get;
- set;
- }
- [Required(ErrorMessage = "Mobile Number Required")]
- [Display(Name = "Mobile Number")]
- [DataType(DataType.Text)]
- [MaxLength(15, ErrorMessage = "Mobile Number not more than 15 characters")]
- public string Mobile
- {
- get;
- set;
- }
- [Required(ErrorMessage = "Email Address Required")]
- [Display(Name = "Email Address")]
- [DataType(DataType.EmailAddress)]
- [MaxLength(150, ErrorMessage = "Email Address not more than 150 characters")]
- public string EmailAddress
- {
- get;
- set;
- }
- }
- }
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.
By right click on CONTROLLER folder, click Add, Controller
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.
- public IEnumerable < FriendModel > GetAllFriends()
- {
- SqlConnection con = new SqlConnection(ConStr);
- SqlCommand cmd = new SqlCommand("Select * From tblFriends", con);
- con.Open();
- SqlDataReader reader = cmd.ExecuteReader();
- List < FriendModel > list = new List < FriendModel > ();
- while (reader.Read())
- {
- FriendModel _friend = new FriendModel();
- _friend.FriendID = Convert.ToInt16(reader["FriendID"]);
- _friend.FriendName = Convert.ToString(reader["FriendName"]);
- _friend.Mobile = Convert.ToString(reader["Mobile"]);
- _friend.Place = Convert.ToString(reader["Place"]);
- _friend.EmailAddress = Convert.ToString(reader["EmailAddress"]);
- list.Add(_friend);
- }
- IEnumerable < FriendModel > data = list;
- return data;
- }
Controller:
Index method implementation.
- public ActionResult Index()
- {
-
- var dataList = _friendRepository.GetAllFriends();
-
- return View(dataList);
- }
View:
Index view of friends list implementation.
Before going further, please build your project.
Right click on friend’s controller index method.
Select
Add View from above said menu.
Now here you can unde stand the above
Add View dialogue box:
- View Name: Index
- View Engine: Razor
- Select Check Box: Create a strongly-typed view.
- Model Class: FriendModel
- 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
- @model IEnumerable < MyFirstMvcApplication.Models.FriendModel > @
- {
- ViewBag.Title = "Index";
- } < 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>
- @foreach(var item in Model)
- { < 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
- {
- id = item.FriendID
- }) | @Html.ActionLink("Details", "Details", new
- {
- id = item.FriendID
- }) | @Html.ActionLink("Delete", "Delete", new
- {
- id = item.FriendID
- }) < /td>< /tr>
- } < /table>
Now press F5 to run application. On the web browser type,
http://localhost:????/friend/indexE.g.: http://localhost:1389/friend/index 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 FRIENDINSERT FRIEND implementations in REPOSITORY, CONTROLLER and VIEW. Repository
InsertNewFriend method code:
-
-
-
- public void InsertNewFriend(FriendModel _friend)
- {
- SqlConnection con = new SqlConnection(ConStr);
- con.Open();
- SqlCommand cmd = new SqlCommand("Insert into tblFriends (FriendName,FriendImage,Place,Mobile) Values(@FriendName,@FriendImage,@Place,@Mobile)", con);
- cmd.Parameters.AddWithValue("@FriendName", _friend.FriendName);
- cmd.Parameters.AddWithValue("@Place", _friend.Place);
- cmd.Parameters.AddWithValue("@Mobile", _friend.Mobile);
- cmd.Parameters.AddWithValue("@EmailAddress", _friend.EmailAddress);
- cmd.ExecuteNonQuery();
- }
Controller:
In friend controller you can see two methods named CREATE.
Submission kind of thing you should use two methods.
- HTTPGET: First load on browser.
- 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.
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.
-
-
- [HttpGet]
- public ActionResult Create()
- {
- return View();
- }
Above code is created for
HttpGet for
Create method.
Now we create code of
HttpPost for
Create method.
-
-
- [HttpPost]
- public ActionResult Create(FormCollection collection)
- {
- try
- {
-
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
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.
-
-
- [HttpPost]
- public ActionResult Create(FriendModel _friendModelData)
- {
- try
- {
- _friendRepository.InsertNewFriend(_friendModelData);
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
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- @model MyFirstMvcApplication.Models.FriendModel
- @
- {
- ViewBag.Title = "Create";
- } < h2 > Create < /h2>
- @using(Html.BeginForm())
- {
- @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)
- @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)
- @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)
- @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)
- @Html.ValidationMessageFor(model => model.EmailAddress) < /div>< p >< input type = "submit"
- value = "Create" / >< /p>< /fieldset>
- } < div > @Html.ActionLink("Back to List", "Index") < /div>
- @section Scripts
- {
- @Scripts.Render("~/bundles/jqueryval")
- }
Now press F5 to run application. On the web browser type,
http://localhost:????/friend/IndexOr 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- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
- namespace MyFirstMvcApplication
- {
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new
- {
- controller = "Friend", action = "Index", id = UrlParameter.Optional
- });
- }
- }
- }
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,
Now, click on
Create button at the bottom. You see model validator executed with the help of JQuery.
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.
Fill the form and submit with
Create button click.
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- public FriendModel GetFriendByFriendID(int FriendID)
- {
- SqlConnection con = new SqlConnection(ConStr);
- SqlCommand cmd = new SqlCommand("Select * From tblFriends where FriendID = " + FriendID, con);
- con.Open();
- SqlDataReader reader = cmd.ExecuteReader();
- FriendModel _friend = new FriendModel();
- _friend.FriendID = Convert.ToInt16(reader["FriendID"]);
- _friend.FriendName = Convert.ToString(reader["FriendName"]);
- _friend.Mobile = Convert.ToString(reader["Mobile"]);
- _friend.Place = Convert.ToString(reader["Place"]);
- _friend.EmailAddress = Convert.ToString(reader["EmailAddress"]);
- return _friend;
- }
UpdateFriendByFriendID code- public void UpdateFriendByFriendID(FriendModel _friend)
- {
- SqlConnection con = new SqlConnection(ConStr);
- con.Open();
- SqlCommand cmd = new SqlCommand("update tblFriends set FriendName =@FriendName ,Place = @Place ,Mobile = @Mobile ,EmailAddress= @EmailAddress where FriendID = " + _friend.FriendID, con);
- cmd.Parameters.AddWithValue("@FriendName", _friend.FriendName);
- cmd.Parameters.AddWithValue("@Place", _friend.Place);
- cmd.Parameters.AddWithValue("@Mobile", _friend.Mobile);
- cmd.Parameters.AddWithValue("@EmailAddress", _friend.EmailAddress);
- cmd.ExecuteNonQuery();
- }
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.
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.
- [HttpGet]
- public ActionResult Edit(int id)
- {
-
- var SelectedFriend = _friendRepository.GetFriendByFriendID(id);
- return View();
- }
-
- [HttpPost]
- public ActionResult Edit(FriendModel _friend)
- {
- try
- {
-
- _friendRepository.UpdateFriendByFriendID(_friend);
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
View
Edit.cshtml- @model MyFirstMvcApplication.Models.FriendModel
- @
- {
- ViewBag.Title = "Edit";
- } < h2 > Edit < /h2>
- @using(Html.BeginForm())
- {
- @Html.ValidationSummary(true) < fieldset > < legend > FriendModel < /legend>
- @Html.HiddenFor(model => model.FriendID) < div class = "editor-label" > @Html.LabelFor(model => model.FriendName) < /div> < div class = "editor-field" > @Html.EditorFor(model => model.FriendName)
- @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)
- @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)
- @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)
- @Html.ValidationMessageFor(model => model.EmailAddress) < /div> < p > < input type = "submit"
- value = "Save" / > < /p> < /fieldset>
- } < div > @Html.ActionLink("Back to List", "Index") < /div>
- @section Scripts
- {
- @Scripts.Render("~/bundles/jqueryval")
- }
Now press F5 to check and test our EDIT functionalities.
When you mouse hover on last record EDIT link button
At bottom left side link will display like the following,
It means when you click on marked blue underline 7th ID number of record will come for edit.
You can see all details of selected row data comes in edit screen.
Now, will change place Jodhpur to Bikaner.
After click on
Save button, Index view will verify that our changes took place or not.
You can see Bikaner place changed successfully.
Next Task is : DETAILSDETAILFRIENDBY 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.
Now we will understand the above AddView dialogue box for DETAILS.
- View Name: Details
- View Engine: Razor
- Select Check Box: Create a strongly-typed view.
- Model Class: FriendModel
- Scaffold Template: Details.
After pressing ADD button, inside VIEW folder of FRIEND, DETAILS.CSHTML view will be created.
- [HttpGet]
- public ActionResult Details(int id)
- {
-
- var SelectedFriend = _friendRepository.GetFriendByFriendID(id);
- return View(SelectedFriend);
- }
View
Details.cshtml- @model MyFirstMvcApplication.Models.FriendModel
-
- @{
- ViewBag.Title = "Details";
- }
-
-
- <h2>Details</h2>
- <fieldset>
- <legend>FriendModel</legend>
- <div class="display-label">
- @Html.DisplayNameFor(model => model.FriendName)
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.FriendName)
- </div>
- <div class="display-label">
- @Html.DisplayNameFor(model => model.Place)
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.Place)
- </div>
- <div class="display-label">
- @Html.DisplayNameFor(model => model.Mobile)
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.Mobile)
- </div>
- <div class="display-label">
- @Html.DisplayNameFor(model => model.EmailAddress)
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.EmailAddress)
- </div>
- </fieldset>
- <p>
- @Html.ActionLink("Edit", "Edit", new { id=Model.FriendID }) |
- @Html.ActionLink("Back to List", "Index")
- </p>
Now press F5 to check and test our DETAILS functionalities.
Now click Details marked blue colour underline.
In DETAILS view by default there is a link of
Edit and
Back to List.
Next Task is : DELETEDELETEFRIENDBY 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.
-
-
-
-
- public void DeleteFriendByFriendID(FriendModel _friend)
- {
- SqlConnection con = new SqlConnection(ConStr);
- con.Open();
- SqlCommand cmd = new SqlCommand("Delete From tblFriends where FriendID = " + _friend.FriendID, con);
- cmd.ExecuteNonQuery();
- }
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.
Now we will understand the above AddView dialogue box for DELETE.
- View Name: Delete
- View Engine: Razor
- Select Check Box: Create a strongly-typed view.
- Model Class: FriendModel
- Scaffold Template: Delete.
After press ingADD button, inside VIEW folder of FRIEND, the DELETE.CSHTML view will be created.
-
-
- [HttpGet]
- public ActionResult Delete(int id)
- {
-
- var SelectedFriend = _friendRepository.GetFriendByFriendID(id);
- return View(SelectedFriend);
- }
-
-
- [HttpPost]
- public ActionResult Delete(FriendModel _friend)
- {
- try
- {
- _friendRepository.DeleteFriendByFriendID(_friend);
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
View
Delete.cshtml- @model MyFirstMvcApplication.Models.FriendModel
-
- @{
- ViewBag.Title = "Delete";
- }
-
-
- <h2>Delete</h2>
- <h3>Are you sure you want to delete this?</h3>
- <fieldset>
- <legend>FriendModel</legend>
- <div class="display-label">
- @Html.DisplayNameFor(model => model.FriendName)
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.FriendName)
- </div>
- <div class="display-label">
- @Html.DisplayNameFor(model => model.Place)
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.Place)
- </div>
- <div class="display-label">
- @Html.DisplayNameFor(model => model.Mobile)
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.Mobile)
- </div>
- <div class="display-label">
- @Html.DisplayNameFor(model => model.EmailAddress)
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.EmailAddress)
- </div>
- </fieldset>
- @using (Html.BeginForm()) {
-
- <p>
- <input type="submit" value="Delete" /> |
- @Html.ActionLink("Back to List", "Index")
-
- </p>
- }
Now press F5 to check and test our DELETE functionalities.
Now click on
Delete button marked with blue colour.
Last record selected for delete. As I click on
Delete button, check
Index view for delete functionalities result.
Full Code
FriendController.csFriendRepository.cs- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data;
- using System.Data.SqlClient;
- using MyFirstMvcApplication.Models;
- using System.Configuration;
- namespace MyFirstMvcApplication.Repository
- {
- public class FriendRepository
- {
- string ConStr = ConfigurationManager.ConnectionStrings["MemberCDACConnectionString"].ConnectionString;
-
-
-
- public IEnumerable < FriendModel > GetAllFriends()
- {
- SqlConnection con = new SqlConnection(ConStr);
- SqlCommand cmd = new SqlCommand("Select * From tblFriends", con);
- con.Open();
- SqlDataReader reader = cmd.ExecuteReader();
- List < FriendModel > list = new List < FriendModel > ();
- while (reader.Read())
- {
- FriendModel _friend = new FriendModel();
- _friend.FriendID = Convert.ToInt16(reader["FriendID"]);
- _friend.FriendName = Convert.ToString(reader["FriendName"]);
- _friend.Mobile = Convert.ToString(reader["Mobile"]);
- _friend.Place = Convert.ToString(reader["Place"]);
- _friend.EmailAddress = Convert.ToString(reader["EmailAddress"]);
- list.Add(_friend);
- }
- IEnumerable < FriendModel > data = list;
- return data;
- }
-
-
-
- public void InsertNewFriend(FriendModel _friend)
- {
- SqlConnection con = new SqlConnection(ConStr);
- con.Open();
- SqlCommand cmd = new SqlCommand("Insert into tblFriends (FriendName,Place,Mobile,EmailAddress) Values(@FriendName,@Place,@Mobile,@EmailAddress)", con);
- cmd.Parameters.AddWithValue("@FriendName", _friend.FriendName);
- cmd.Parameters.AddWithValue("@Place", _friend.Place);
- cmd.Parameters.AddWithValue("@Mobile", _friend.Mobile);
- cmd.Parameters.AddWithValue("@EmailAddress", _friend.EmailAddress);
- cmd.ExecuteNonQuery();
- }
-
-
-
- public FriendModel GetFriendByFriendID(int FriendID)
- {
- SqlConnection con = new SqlConnection(ConStr);
- SqlCommand cmd = new SqlCommand("Select * From tblFriends where FriendID = " + FriendID, con);
- con.Open();
- SqlDataReader reader = cmd.ExecuteReader();
- FriendModel _friend = new FriendModel();
- while (reader.Read())
- {
- _friend.FriendID = Convert.ToInt16(reader["FriendID"]);
- _friend.FriendName = Convert.ToString(reader["FriendName"]);
- _friend.Mobile = Convert.ToString(reader["Mobile"]);
- _friend.Place = Convert.ToString(reader["Place"]);
- _friend.EmailAddress = Convert.ToString(reader["EmailAddress"]);
- }
- return _friend;
- }
-
-
-
-
- public void UpdateFriendByFriendID(FriendModel _friend)
- {
- SqlConnection con = new SqlConnection(ConStr);
- con.Open();
- SqlCommand cmd = new SqlCommand("update tblFriends set FriendName =@FriendName ,Place = @Place ,Mobile = @Mobile ,EmailAddress= @EmailAddress where FriendID = " + _friend.FriendID, con);
- cmd.Parameters.AddWithValue("@FriendName", _friend.FriendName);
- cmd.Parameters.AddWithValue("@Place", _friend.Place);
- cmd.Parameters.AddWithValue("@Mobile", _friend.Mobile);
- cmd.Parameters.AddWithValue("@EmailAddress", _friend.EmailAddress);
- cmd.ExecuteNonQuery();
- }
-
-
-
-
- public void DeleteFriendByFriendID(int FriendID)
- {
- SqlConnection con = new SqlConnection(ConStr);
- con.Open();
- SqlCommand cmd = new SqlCommand("Delete From tblFriends where FriendID = " + FriendID, con);
- cmd.ExecuteNonQuery();
- }
- }
- }
We had achieved the following functionalities,
- List of Friends
- Insert a Friend
- Update a Friend
- Delete a Friend
If you have any doubt feel free to ask.