Tuesday, 12 August 2014

Insert, Update, Delete Operation In Asp.Net MVC Using Entity Framework C#.Net

8/12/2014 - By Pranav Singh 39

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.

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: @@{<a href="/Home/Edit/?stuId=@item.Id">Edit</a>}
),
                grid.Column(""null, format: @@{<a href="/Home/Delete/?stuId=@item.Id">Delete</a>}
)
                ), 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.

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

39 comments:

  1. 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.

    ReplyDelete
    Replies
    1. Hi Ananth thanks for visiting aspdotnet-pools.com. i will try to provide you an example as per your requirement.

      Delete
  2. Hi Ananth i have written and article as per you description. have a look of this article i hope this will help you.

    http://www.aspdotnet-pools.com/2014/08/fileupload-control-inside-webgrid-to.html

    ReplyDelete
  3. Please give me exapmle why we should use mvc.framwork rather than web forms..

    ReplyDelete
  4. Hi This is nice post I have learn so much from this post. Thanks for posting.

    ReplyDelete
  5. Keep it up Good Working @admin Pranav

    ReplyDelete
  6. I want to do CRUD operations for three tables and use only Four Views...??

    ReplyDelete
  7. how to insert textbox values in database(sql server) in mvc

    ReplyDelete
  8. Hi Meena the article is already there in which you have commented.

    ReplyDelete
  9. Hey it's really good article.. as I am beginner, it helps me a lot to build a basic crud functionality. Thank you..

    ReplyDelete
  10. vry nice
    vry neatly explained
    u may also read this:
    http://www.mindstick.com/Articles/30148105-6777-467a-9ecc-82a2118387d0/Insert%20Update%20Delete%20Records%20in%20CSharp%20NET

    ReplyDelete
  11. it's really good one post

    ReplyDelete
  12. Replies
    1. Thanks for your valuable comment

      Delete
    2. Sir I m new in MVC
      I am creating same app at my end
      May i know Where is StudentManagerEntitie class.

      Delete
    3. 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.
      Here StudentManagerEntitie s the entity class file name.

      Delete
    4. Dear Pranav Singh Plz Tell ME step by step like class name table name path all plz reply

      Delete
  13. Good post...
    just wondering how to update student grid upon new record inserted, if both grid and create new record form are in same view..

    Thanks!

    ReplyDelete
  14. Insert, Update, Delete Operation In Asp.Net MVC Using Dynamic CRM C#.Net ,CRUD Functionality pls send immidiatly..

    ReplyDelete
  15. You can find simple code here :

    http://www.dotnetcode2u.com/2015/08/insert-update-delete-edit-select-in-3.html

    ReplyDelete
  16. Plz Tell Me Step By Step Means Like Class Name Table Name

    ReplyDelete
    Replies
    1. Hi Vwnkat.
      It's already there. please check the above code.

      Delete
  17. Good ...but you may tell me it is possible in entity framework...??

    ReplyDelete
  18. Good ...but you may tell me it is possible in entity framework...??

    ReplyDelete
    Replies
    1. Hi.
      I have been written by using entity framework.

      Delete
  19. Can you please tell what this class doing "StudentManagerEntitie "

    ReplyDelete
  20. You can find simple code here:
    http://www.dotnetcode2u.com/2015/08/mvc-4-how-to-perform-insert-update.html

    ReplyDelete
  21. 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

    ReplyDelete
    Replies
    1. It's totally depend upon your project requirement. i prefer always blank project template. bczwe can manage it as per our need

      Delete
  22. very nice tutorials i have learnt so much from this

    keep updating us sir

    ReplyDelete

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top