This will show you how you can perform insert, update, delete
operation in an mvc application using entity framework by linq using C#.net.
This is called CRUD functionality. This you can use in MVC3, MVC4, MVC5.
Some of my previous articles are as follows:
MVC
WebGrid Custom paging With Page no and Shorting Data Using C#.Net, MVC
WebGrid Custom paging With Page no and Shorting Data Using C#.Net, Code
to Dynamically Bind Image To Asp.net MVC WebGrid, Bind
and Retrieve ListBox Selected Value in MVC Using C#.Net, Bind
DropDownList Using Entity Framework in ASP.Net MVC Using C#.
Here is our sql table:
So for this article first we will create a new asp.net application
in this we will add a model file in this model file add the below class code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProjectDemo_MVC.Models
{
public class StudentListModel
{
public
List<StudentList>
StudentListCollction { get; set; }
public
StudentList StudentListDetail { get; set; }
}
public class StudentList
{
public
string Id { get;
set; }
public
string Name { get;
set; }
public
string Address { get;
set; }
public
string Section { get;
set; }
public
int Marks { get;
set; }
}
}
|
After creating model we will access entity table.
Now we will come to controller and add the below code for
binding the webgrid. Controller code is as follows:
///
/// For getting detail list of student
///
public ActionResult Index()
{
StudentListModel objstudentlistmodel = new StudentListModel();
objstudentlistmodel.StudentListCollction = new List<StudentList>();
objstudentlistmodel.StudentListCollction = GetStudentList();
return View(objstudentlistmodel);
}
///
/// Get student record
///
public List<StudentList> GetStudentList()
{
List<StudentList> objStudent = new List<StudentList>();
/*Create instance of entity model*/
StudentManagerEntitie objentity = new StudentManagerEntitie();
/*Getting data from database for user validation*/
var _objuserdetail = (from data in objentity.StudentDetails
select data);
foreach (var item in _objuserdetail)
{
objStudent.Add(new StudentList { Id = item.Id, Name = item.Name, Section = item.Section, Marks = (int)item.Maks, Address = item.Address });
}
return objStudent;
}
|
Now in view add the below code.
@model ProjectDemo_MVC.Models.StudentListModel
@{
ViewBag.Title = "StudentDetailList";
}
<style>
table, td, th
{
border:
1px solid green;
border-collapse:
collapse;
width:
30%;
}
th
{
border:
1px solid black;
background-color:
green;
color:
white;
}
</style>
@using
(@Html.BeginForm("Index", "Home"))
{
var grid
= new WebGrid(Model.StudentListCollction,
canSort: false);
<div>
@grid.GetHtml(columns:
grid.Columns
(
grid.Column("Name", "Stud
Name"),
grid.Column("Marks", "Marks"),
grid.Column("Section", "Section"),
grid.Column("Address", "Address"),
grid.Column("", null,
format: @
),
grid.Column("", null, format: @
)
), mode: WebGridPagerModes.Numeric)
</div>
<div>
<a href="/Home/Create/">Add New Record</a></div>
}
|
In this I have added link for edit and delete. So run the page
to view the output.
After this again come to you controller. Now we will write
code to create a new record.
SAVE NEW RECORD:
So here is the code for HttpGet and HttpPost method as
follows.
///
/// Create Record
///
public ActionResult Create()
{
StudentListModel objstudentlistmodel = new StudentListModel();
return View(objstudentlistmodel);
}
///
/// Post method for save data
///
[HttpPost]
public ActionResult Create(StudentListModel objstudentlistmodel)
{
try
{
/*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
StudentList _objstudentlist = new StudentList();
_objstudentlist.Id = Guid.NewGuid().ToString();
_objstudentlist.Name = objstudentlistmodel.StudentListDetail.Name;
_objstudentlist.Marks = objstudentlistmodel.StudentListDetail.Marks;
_objstudentlist.Address = objstudentlistmodel.StudentListDetail.Address;
_objstudentlist.Section = objstudentlistmodel.StudentListDetail.Section;
Save(_objstudentlist);
/*Retrived Data*/
List<StudentList> objfilelist = new List<StudentList>();
objfilelist = GetStudentList();
objstudentlistmodel.StudentListCollction = objfilelist;
objstudentlistmodel.StudentListDetail = new StudentList();
ViewBag.Message = "Data saved successfully.";
}
catch
{
ViewBag.Message = "Error while saving data.";
}
return View(objstudentlistmodel);
}
///
/// This function save data to database
///
public int Save(StudentList _objstudentlist)
{
StudentManagerEntitie objentity = new StudentManagerEntitie();
StudentDetail objstudentdetail = new StudentDetail();
objstudentdetail.Id = _objstudentlist.Id;
objstudentdetail.Name = _objstudentlist.Name;
objstudentdetail.Maks = _objstudentlist.Marks;
objstudentdetail.Section = _objstudentlist.Section;
objstudentdetail.Address = _objstudentlist.Address;
objentity.StudentDetails.AddObject(objstudentdetail);
/*Save data to database*/
objentity.SaveChanges();
return 1;
}
|
Now create the view and add the below code into the view.
@model ProjectDemo_MVC.Models.StudentListModel
@{
ViewBag.Title = "Insert,
Update, Delete Operation In Asp.Net MVC Using Entity Framework C#.Net ,CRUD
Functionality";
}
<style>
.container
{
width:
100%;
text-align:
center;
}
.left
{
float:
left;
width:
150px;
}
</style>
@using
(Html.BeginForm("Create", "Home", FormMethod.Post))
{
<div>
<table width="20%" cellpadding="5" cellspacing="5" border="1" style="border: 1 solid black;
border-collapse: collapse;">
<tr>
<td align="right">
Name :
</td>
<td align="left">@Html.TextBoxFor(m =>
m.StudentListDetail.Name)
</td>
</tr>
<tr>
<td align="right">
Address :
</td>
<td align="left">@Html.TextBoxFor(m =>
m.StudentListDetail.Address)
</td>
</tr>
<tr>
<td align="right">
Section :
</td>
<td align="left">@Html.TextBoxFor(m =>
m.StudentListDetail.Section)
</td>
</tr>
<tr>
<td align="right">
Marks :
</td>
<td align="left">@Html.TextBoxFor(m => m.StudentListDetail.Marks)
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Save" />
<a href="/Home/index/" >Back</a>
<div style="color: Red">@ViewBag.Message</div>
</td>
</tr>
</table>
</div>
}
|
Now we have completed with save operation. Now run the page
to check the output.
Now click on save button. You will get the save success data
message.
Press back button to check the final record
Now Let’s code for delete record.
DELETE RECORD:
In this we have used below mention code to delete the
record.
public ActionResult Delete()
{
string
studentId = Request.QueryString["stuId"].ToString();
StudentManagerEntitie
objentity = new StudentManagerEntitie();
StudentDetail
objstudentdetail = new StudentDetail();
objstudentdetail = (from data in
objentity.StudentDetails
where data.Id == studentId
select data).FirstOrDefault();
StudentList
_objstudentlist = new StudentList();
_objstudentlist.Id = studentId;
_objstudentlist.Name =
objstudentdetail.Name;
_objstudentlist.Address =
objstudentdetail.Address;
_objstudentlist.Marks = (int)objstudentdetail.Maks;
_objstudentlist.Section =
objstudentdetail.Section;
StudentListModel
objstudentlistmodel = new StudentListModel();
objstudentlistmodel.StudentListDetail
= _objstudentlist;
return
View(objstudentlistmodel);
}
///
/// This method delete function
///
[HttpPost]
public ActionResult Delete(string Id = "")
{
StudentManagerEntitie objentity = new StudentManagerEntitie();
StudentDetail objstudentdetail = new StudentDetail();
objstudentdetail.Id = Id;
objentity.StudentDetails.Attach(objstudentdetail);
objentity.DeleteObject(objstudentdetail);
/*Save data to database*/
objentity.SaveChanges();
return RedirectToAction("/Index/");
// return RedirectToAction("Index");
}
|
Now create the view and add the below code.
@model ProjectDemo_MVC.Models.StudentListModel
@{
ViewBag.Title = "Delete";
}
@using
(Html.BeginForm("Delete", "Home", FormMethod.Post))
{
<div>
<table width="20%" cellpadding="5" cellspacing="5" border="1" style="border: 1 solid black;
border-collapse: collapse;">
<tr>
<td align="right">
Name :
</td>
<td align="left">@Html.DisplayFor(m =>
m.StudentListDetail.Name)
@Html.Hidden("Id",Model.StudentListDetail.Id)
</td>
</tr>
<tr>
<td align="right">
Address :
</td>
<td align="left">@Html.DisplayFor(m =>
m.StudentListDetail.Address)
</td>
</tr>
<tr>
<td align="right">
Section :
</td>
<td align="left">@Html.DisplayFor(m =>
m.StudentListDetail.Section)
</td>
</tr>
<tr>
<td align="right">
Marks :
</td>
<td align="left">@Html.DisplayFor(m =>
m.StudentListDetail.Marks)
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Delete" />
<div style="color: Red">@ViewBag.Message</div>
</td>
</tr>
</table>
</div>
}
|
In above code first we have displayed the record and after that perform the delete operation as user click on delete button. Now run the page and check the output.
Now click on delete link
After this click on delete button. After deleting your final
output.
Now let’s perform some update operation.
EDIT RECORD:
In this first we will use the below code for edit.
///
/// This method display record for edit
///
public ActionResult Edit()
{
string studentId = Request.QueryString["stuId"].ToString();
StudentManagerEntitie objentity = new StudentManagerEntitie();
StudentDetail objstudentdetail = new StudentDetail();
objstudentdetail = (from data in objentity.StudentDetails
where data.Id == studentId
select data).FirstOrDefault();
StudentList _objstudentlist = new StudentList();
_objstudentlist.Id = studentId;
_objstudentlist.Name = objstudentdetail.Name;
_objstudentlist.Address = objstudentdetail.Address;
_objstudentlist.Marks = (int)objstudentdetail.Maks;
_objstudentlist.Section = objstudentdetail.Section;
StudentListModel objstudentlistmodel = new StudentListModel();
objstudentlistmodel.StudentListDetail = _objstudentlist;
return View(objstudentlistmodel);
}
///
/// This method edit function
///
[HttpPost]
public ActionResult Edit(StudentListModel objstudentlistmodel, string Id = "")
{
StudentManagerEntitie objentity = new StudentManagerEntitie();
StudentDetail objdstudent = objentity.StudentDetails.First(m => m.Id == Id);
objdstudent.Name = objstudentlistmodel.StudentListDetail.Name;
objdstudent.Address = objstudentlistmodel.StudentListDetail.Address;
objdstudent.Maks = objstudentlistmodel.StudentListDetail.Marks;
objdstudent.Section = objstudentlistmodel.StudentListDetail.Section;
/*Save data to database*/
objentity.SaveChanges();
return RedirectToAction("/Index/");
}
|
Now we generate the view and add the below cod in it.
@model ProjectDemo_MVC.Models.StudentListModel
@{
ViewBag.Title = "Edit";
}
@using
(Html.BeginForm("Edit", "Home", FormMethod.Post))
{
<div>
<table width="20%" cellpadding="5" cellspacing="5" border="1" style="border: 1 solid black;
border-collapse: collapse;">
<tr>
<td align="right">
Name :
</td>
<td align="left">@Html.TextBoxFor(m =>
m.StudentListDetail.Name)
@Html.Hidden("Id",
Model.StudentListDetail.Id)
</td>
</tr>
<tr>
<td align="right">
Address :
</td>
<td align="left">@Html.TextBoxFor(m =>
m.StudentListDetail.Address)
</td>
</tr>
<tr>
<td align="right">
Section :
</td>
<td align="left">@Html.TextBoxFor(m =>
m.StudentListDetail.Section)
</td>
</tr>
<tr>
<td align="right">
Marks :
</td>
<td align="left">@Html.TextBoxFor(m => m.StudentListDetail.Marks)
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Update" />
<div style="color: Red">@ViewBag.Message</div>
</td>
</tr>
</table>
</div>
}
|
Now we have done. Just click on edit link post back will take place and it will display the record in textbox. Just change the record and click on update button.
After successful update just check the output.
Now we have done . Download the article and try by your
self.
hi is it possible to upload file using webgrid.if yes please give me some idea about that are post example to related to that.
ReplyDeleteHi Ananth thanks for visiting aspdotnet-pools.com. i will try to provide you an example as per your requirement.
DeleteHi Ananth i have written and article as per you description. have a look of this article i hope this will help you.
ReplyDeletehttp://www.aspdotnet-pools.com/2014/08/fileupload-control-inside-webgrid-to.html
Really good
ReplyDeleteThanks for your valuable comment
DeletePlease give me exapmle why we should use mvc.framwork rather than web forms..
ReplyDeleteHi please check the below link for answer of your question
Deletehttp://www.codeproject.com/Articles/556995/MVC-interview-questions-with-answers#What%20are%20the%20benefits%20of%20using%20MVC
http://www.dotnetfunda.com/interviews/show/5735/what-are-the-advantages-of-using-aspnet-mvc
Hi This is nice post I have learn so much from this post. Thanks for posting.
ReplyDeleteThanks for your valuable comment....
DeleteKeep it up Good Working @admin Pranav
ReplyDeleteI want to do CRUD operations for three tables and use only Four Views...??
ReplyDeletehow to insert textbox values in database(sql server) in mvc
ReplyDeleteHi Meena the article is already there in which you have commented.
ReplyDeleteHey it's really good article.. as I am beginner, it helps me a lot to build a basic crud functionality. Thank you..
ReplyDeletevry nice
ReplyDeletevry neatly explained
u may also read this:
http://www.mindstick.com/Articles/30148105-6777-467a-9ecc-82a2118387d0/Insert%20Update%20Delete%20Records%20in%20CSharp%20NET
it's really good one post
ReplyDeletereally good nice job.....
ReplyDeleteThanks for your valuable comment
DeleteSir I m new in MVC
DeleteI am creating same app at my end
May i know Where is StudentManagerEntitie class.
When you add an entity file in your project at that time you define the entity class file name. as i have used in it .StudentManagerEntitie.
DeleteHere StudentManagerEntitie s the entity class file name.
Dear Pranav Singh Plz Tell ME step by step like class name table name path all plz reply
DeleteGood post...
ReplyDeletejust wondering how to update student grid upon new record inserted, if both grid and create new record form are in same view..
Thanks!
Plz Tell Me step by step
DeleteGood Post.
ReplyDeleteInsert, Update, Delete Operation In Asp.Net MVC Using Dynamic CRM C#.Net ,CRUD Functionality pls send immidiatly..
ReplyDeleteYou can find simple code here :
ReplyDeletehttp://www.dotnetcode2u.com/2015/08/insert-update-delete-edit-select-in-3.html
Plz Tell Me Step By Step Means Like Class Name Table Name
ReplyDeleteHi Vwnkat.
DeleteIt's already there. please check the above code.
Good ...but you may tell me it is possible in entity framework...??
ReplyDeleteGood ...but you may tell me it is possible in entity framework...??
ReplyDeleteHi.
DeleteI have been written by using entity framework.
Can you please tell what this class doing "StudentManagerEntitie "
ReplyDeleteYou can find simple code here:
ReplyDeletehttp://www.dotnetcode2u.com/2015/08/mvc-4-how-to-perform-insert-update.html
Can u please tell me which template i have to use Empty Or Internet Application...And also tell me how to add view for create delete edit...This will helpful for fresher
ReplyDeleteIt's totally depend upon your project requirement. i prefer always blank project template. bczwe can manage it as per our need
Deletevery nice tutorials i have learnt so much from this
ReplyDeletekeep updating us sir
Thanks for your valuable comment
DeleteVery Help Full Article.
ReplyDeletecnnhub
Thanks for your comment.
Delete