ASP.NET MVC

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.

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:

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

  • Select the click on “Next”.

  • Select “Entity Framework 6.x”.

  • 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" >
  • 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" >

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" >

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

I hope you guys understand how we can do that.

Let me know if you face any difficulties.

Happy Coding {;} ????

Nayan Raval

Nayan Raval is a MEAN Stack .Net Developer has extensive experience with designing and developing enterprise-scale applications. Key Areas Of Expertise: • ASP.NET Core MVC • ASP.NET Core Web API • C# • ASP.NET MVC 5 • Angular All versions • HTML5 • CSS3 / SCSS • Bootstrap • JavaScript • Azure • JQuery Databases and related • Microsoft SQL server MSSQL • PostgreSQL • Entity Framework (EF) • LINQ UI Frameworks • Kendo UI • Telerik • JQuery UI • Prime NG and Material UI API Integration • SignalR • DateDog • Twilio Voice Call And Message • Stripe • SendGrid (Email Camping) • Checkr • Zoom Video Call • Auth0 • Elastic Search • Quartz - Scheduler • JWT Token • Google Calendar

View Comments

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago