Crud Operation Using Partial View In MVC Razor

In this article, we will learn about how we can perform crud operations using Partial View is like a web user control in ASP .NET applications. Partial Views and User Controls serve the same purpose.

Uses of Partial Views : 

  • A partial view can be used as a reusable component that can be called or used from multiple and different views
  • To break up large markup files into smaller components.
  • A partial view contains reusable mark-up if you want to render from inside multiple views.
  • The partial view is used to render a consistent look like header, footer, comments and so on.

Create a new project and select the MVC pattern.

MVC Start

Select MVC pattern

Here we use Entity Framework 6 with MVC5 :

Firstly install the Entity framework from the Package manager Console

Install-Package EntityFramework
  • First here is our SQL table:

table

  • So for this tutorial first we created a new empty MVC application. In this we will add an ADO .NET entity data model to the Model as in the following:
  • Select Data -> ADO.NET Entity Data Model. 
  • Select “EF Designer from database” :

  • Then select Server name and Database name.

Database

  • Select the click on “Next”.

DBEntities

  • Select “Entity Framework 6.x”.

Entitie

  • Then select the table.

  • Now Model1.edmx has been added to the Model folder.

  • Let’s get started.

Navigate to Models -> create a new class as Student.cs.

public class Student
   {
       public int ID { get; set; }

       [Required]
       public string StudentName { get; set; }

       [Required]
       public string Class { get; set; }

       [Required]
       public string Course { get; set; }
   }
  • Now, open the Home Controller and add the code in it.
using PartialViewCrudDemo.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PartialViewCrudDemo.Controllers
{
    public class HomeController : Controller
    {
        private DBStudentEntities _context = new DBStudentEntities();
        public ActionResult Index()
        {
            return View(_context.tblStudents.ToList());
        }

        [HttpPost]
        public ActionResult MyCreatePartial(tblStudent stud)
        {
            var stuName = stud.StudentName;
            var stuclass = stud.Class;
            var stuCourse = stud.Course;

            if (!string.IsNullOrEmpty(stuName) && !string.IsNullOrEmpty(stuclass) && !string.IsNullOrEmpty(stuCourse))
            {
                _context.tblStudents.Add(stud);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }
            return PartialView("CreatePartial");
        }

        [HttpGet]
        public ActionResult GetByID(int ID)
        {
            tblStudent stuTable = _context.tblStudents.Find(ID);
            if (stuTable == null)
            {
                return HttpNotFound();
            }
            return PartialView("EditPartial" , stuTable);
        }
        public ActionResult GetByDeleteID(int ID)
        {
            tblStudent stuTable = _context.tblStudents.Find(ID);
            if (stuTable == null)
            {
                return HttpNotFound();
            }
            return PartialView("DeletePartial", stuTable);
        }

        public ActionResult MyEditPartial(tblStudent stuTable)
        {
            var stuName = stuTable.StudentName;
            var stuclass = stuTable.Class;
    
            if (!string.IsNullOrEmpty(stuName) && !string.IsNullOrEmpty(stuclass))
            {
                _context.Entry(stuTable).State = EntityState.Modified;
                _context.SaveChanges();
                return RedirectToAction("Index");
            }
            return PartialView("EditPartial");
        }

        [HttpPost]
        public ActionResult MyDeletePartial(int ID)
        {
            tblStudent tblStu = _context.tblStudents.Find(ID);
            _context.tblStudents.Remove(tblStu);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}
  • Now, Firstly we can Home -> Index.cshtml Add some code and the create -> Add three Partial View :

Index.cshtml File:

@model IEnumerable<PartialViewCrudDemo.Models.tblStudent>
@{
    ViewBag.Title = "Home Page";
}

<div class="container">
    <h2>Record</h2>
    <input type="button" class="btn btn-primary"  id="addData"  value="Add" onclick="AddData();"/>
    <br /><br />

    <table class="table table-bordered table-hover">
        <tr>
            <th style="display:none;">
                @Html.DisplayNameFor(model => model.ID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.StudentName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Class)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Course)
            </th>
            <th>Action</th>
        </tr>

        @foreach (var i in Model)
        {
            <tr>
                <td style="display:none;">
                    @Html.DisplayFor(modelItem => i.ID)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => i.StudentName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => i.Class)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => i.Course)
                </td>
                <td>
                    <a class="btn btn-info btn-sm" id="@i.ID" onclick="GetbyID(this.id)">Edit</a>
                    <a class="btn btn-danger btn-sm" id="@i.ID" onclick="GetbyDelID(this.id)"> Delete </a>
                </td>
            </tr>
        }
    </table>
</div>
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title"> Student Data</h4>
            </div>
            <div class="modal-body">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

@section scripts{
    <script>
        function AddData() {
            $.post("@Url.Action("MyCreatePartial", "Home")",
                function (data) {
                    $('.modal-body').html(data);
                });
                $("#myModal").modal("show");
        }

        function GetbyID(ID) {
              $.get("@Url.Action("GetByID", "Home")/" + ID,
                function (data) {
                    $('.modal-body').html(data);
                });
                $("#myModal").modal("show");
        }
         function GetbyDelID(ID) {
              $.get("@Url.Action("GetByDeleteID", "Home")/" + ID,
                function (data) {
                    $('.modal-body').html(data);
                });
                $("#myModal").modal("show");
        }

        function EditData() {
             $.post("@Url.Action("MyEditPartial", "Home")",
                function (data) {
                    $('.modal-body').html(data);
                });
                $("#myModal").modal("show");
        }

        function Delete(ID) {
            $.post("@Url.Action("MyDeletePartial", "Home")/" + ID,
                function (data) {
                   $('.modal-body').html(data);
                });
            $("#myModal").modal("show");
        }
    </script>
}
  • Select Shared ->  Add -> View

1.  CreatePartial.cshtml     

  • As its following add two more Partial View :

Code :  CreatePartial.cshtml

@model PartialViewCrudDemo.Models.Student

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)

        <h3>Add Employee</h3>

        <div class="editor-label">
            @Html.LabelFor(model => model.StudentName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.StudentName, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.StudentName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Class)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Class, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Class)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Course)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Course, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Course)
        </div>
        <p>
            <input type="submit" value="Save" class="btn btn-primary" onclick="AddData();"/>
        </p>
    }
</body>
</html>

Code :  EditPartial.cshtml

@model PartialViewCrudDemo.Models.tblStudent

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Edit Record Student</title>
</head>
<body>
    @using (Html.BeginForm("MyEditPartial", "Home"))
    {
        @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.ID)
        <div class="form-group">
            @Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Class, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Class, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Class, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Course, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Course, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Course, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" onclick="EditData()" />
            </div>
        </div>
    </div>
    }
</body>
</html>

Code : DeletePartial.cshtml

@model PartialViewCrudDemo.tblStudent

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script>
    $(document).ready(function () {
        $('#DelButton').click(function () {
            alert("Confirm Delete..");
            $("#dialog").dialog();
        });
    });
    </script>
    <meta name="viewport" content="width=device-width" />
</head>
<body>
    <h3>Are you sure you want to delete this?</h3>

    <div class="display-label" style="display:none;">
        @Html.DisplayNameFor(model => model.ID)
    </div>
    <div class="display-field" style="display:none;">
        @Html.DisplayFor(model => model.ID)
    </div>
    <div class="display-label ">
        <label style="font-family:'Bookman Old Style';">Student Name</label>
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.StudentName)
    </div>
    <div class="display-label">
        <label style="font-family:'Bookman Old Style';">Class</label>
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Class)
    </div>
    <div class="display-label">
        <label style="font-family:'Bookman Old Style';">Course</label>
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Course)
    </div>
    @using (Html.BeginForm("MyDeletePartial", "Home"))
    {
    <p>
        <br/>
        @Html.HiddenFor(model => model.ID)
        <input type="submit" value="Delete" id="DelButton" class="btn btn-danger" />
    </p>
    }
</body>
</html>


That’s it.

OUTPUT

Output

I hope you guys understand how we can do that.

Let me know if you face any difficulties.

Happy Coding {;} ????

2 Comments

  1. Karishma

    hi sir i got this code.
    but i want to do same with stored procedure.
    how can i do?

    0
    0
    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories