ASP.NET MVC Tutorials

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, MVC6.
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 < span style = "font-family: "consolas"; font-size: 9.5pt;" > ProjectDemo_MVC.Models.< span style = "color: #2b91af;" > StudentListModel < o:p >
@{
    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(< span style = "color: #a31515;" > "Index" , < span style = "color: #a31515;" > "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: @@{<a href="/Home/Edit/?stuId=@item.Id">Edit < span style = "color: blue;" > </< span style = "color: maroon;" > a < span style = "color: blue;" > > } ),< o:p >< br > < div class="MsoNormal" style="margin-bottom: 0.0001pt;">                 grid.Column( "" null , format: @@{<a href="/Home/Delete/?stuId=@item.Id">Delete</ a < span style="color: blue;">>}
)
                ), 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 < span style = "font-family: "consolas"; font-size: 9.5pt;" > ProjectDemo_MVC.Models.< span style = "color: #2b91af;" > StudentListModel < o:p >
@{
    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 < span style = "font-family: "consolas"; font-size: 9.5pt;" > ProjectDemo_MVC.Models.< span style = "color: #2b91af;" > StudentListModel < o:p >
@{
    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 < span style = "font-family: "consolas"; font-size: 9.5pt;" > ProjectDemo_MVC.Models.< span style = "color: #2b91af;" > StudentListModel < o:p >
@{
    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>
}
After successful update just check the output.
;