This article covers how to run CRUD (Create, Edit, Update, Delete, Details) operations in a Single View(page) using JavaScript and AJAX calls in MVC. And also, how to create a JSON file and filter (Search) data from that.
Also, I am using Entity Framework for this sample project.
So, create an ASP.NET project. For this, follow the given steps
- Open Visual Studio. Select New Project.
- In Visual C# tab, select ASP.NET Web Application.
- Now, select an Empty Project. In "Add folders and core reference for:" section, select MVC and click OK.
- Now, right click on your Solution and add another Project as Class Library (as I am using Entity Framework).
- Add a Class in that Class Library, as shown below:
- public class Users
- {
- [Key]
- public int Id { get; set; }
- public string Name { get; set; }
- public string Address { get; set; }
- public string Phone_Number { get; set; }
- }
Now, right click on your Class Library and install Entity Framework via NuGet.
Now, add folder in Class Library, named as Context and add a Class in it, as shown below.
- public class JsonContext:DbContext
- {
- public DbSet<Users> ObjUser { get; set; }
- }
Now, in Web.Config file of Project, add the following Connection string.
- <connectionStrings>
- <add name="JsonContext" connectionString="Provide your credentials" providerName="System.Data.SqlClient" />
- </connectionStrings>
Add the Class Library in a reference of your Project and build the Solution. Add the Empty Controller in controllers folder of the Project.
Now, Add the following ActionResult method to your Controller.
- public ActionResult Index()
- {
- using (JsonContext context = new JsonContext())
- {
- return View(context.ObjUser.ToList());
- }
- }
Now, in the View of the index method, write the following code for displaying the list of the users in a table with edit, delete, and details option for each.
- @model IEnumerable<JsonEntity.Users>
-
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>Index</h2>
-
- <table id="tableUser" class="table">
- <tr>
- <th>
- @Html.DisplayNameFor(model => model.Name)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Address)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Phone_Number)
- </th>
- <th></th>
- </tr>
-
- @foreach (var item in Model) {
- <tr id="TableData">
- <td>
- @Html.DisplayFor(modelItem => item.Name)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Address)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Phone_Number)
- </td>
- <td>
- <input type="button" id="btnEditUser" value="Edit" onclick="EditUser(@item.Id)" class="btn btn-default" /> |
- <input type="button" id="btnDetailUser" value="Details" onclick="Details(@item.Id)" class="btn btn-default" /> |
- <input type="button" id="btnDeleteUser" value="Delete" onclick="Delete(@item.Id)" class="btn btn-default" />
- </td>
- </tr>
- }
-
- </table>
Here, your users list would be empty. To create a user, update your View as the following.
- @model IEnumerable<JsonEntity.Users>
-
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>Index</h2>
- <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
- <p>
- <input type="button" id="btnCreateUser" value="Create User" class="btn btn-default" />
- </p>
-
-
- <table id="tableUser" class="table"></table>
-
-
- <div id="CreateUser" class="form-horizontal">
- <h4>Users</h4>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- <label class = "control-label col-md-2">Name</label>
- <div class="col-md-10">
- <input class="form-control" type="text" name="Name" id="Name"/>
- </div>
- </div>
-
- <div class="form-group">
- <label class="control-label col-md-2">Address</label>
- <div class="col-md-10">
- <input class="form-control" type="text" name="Address" id="Address" />
- </div>
- </div>
-
- <div class="form-group">
- <label class="control-label col-md-2">Phone Number</label>
- <div class="col-md-10">
- <input class="form-control" type="text" name="PhoneNumber" id="PhoneNumber" />
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="button" id="btnCreate"value="Create" class="btn btn-default" />
- <input type="button" id="btnJson" value="Create Json" class="btn btn-default" />
- </div>
- </div>
- </div>
Now, add a JavaScript to create a User.
- <script type="text/javascript">
- $("#btnCreate").click(function () {
- var objUser = {};
- objUser.Name = $("#Name").val();
- objUser.Address = $("#Address").val();
- objUser.Phone_Number = $("#PhoneNumber").val();
- $.post("/Users/CreateUser", { objUser: objUser }, function (data)
- {
- if (data != null) {
- alert("User Created");
- location.reload();
- }
- else {
- alert("Error");
- }
- });
- })
- </script>
Add a JsonResult method in your Controller.
- [HttpPost]
- public JsonResult CreateUser(Users objUser)
- {
- try
- {
- using (JsonContext context = new JsonContext())
- {
- context.ObjUser.Add(objUser);
- context.SaveChanges();
- return Json(objUser, JsonRequestBehavior.AllowGet);
- }
- }
- catch (Exception ex)
- {
- return null;
- }
- }
Now, for editing the Users, update your Index View with the code shown below.
- <div id="CreateUser" class="form-horizontal"></div>
-
- <div class="form-horizontal" id="EditUser">
- <h4>Users</h4>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- <input type="hidden" id="IdEdit" name="IdEdit"/>
- <label class="control-label col-md-2">Name</label>
- <div class="col-md-10">
- <input class="form-control" type="text" name="NameEdit" id="NameEdit" />
- </div>
- </div>
-
- <div class="form-group">
- <label class="control-label col-md-2">Address</label>
- <div class="col-md-10">
- <input class="form-control" type="text" name="AddressEdit" id="AddressEdit" />
- </div>
- </div>
-
- <div class="form-group">
- <label class="control-label col-md-2">Phone Number</label>
- <div class="col-md-10">
- <input class="form-control" type="text" name="PhoneNumberEdit" id="PhoneNumberEdit" />
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="button" value="Save" id="btnSaveEdit" class="btn btn-default" />
- </div>
- </div>
- </div>
Add another JavaScript function in your View.
- function EditUser(Id)
- {
- $.get("/Users/EditUserJ",{Id:Id},function(data){
- if(data!=null)
- {
- $("#tableUser").hide();
- $("#CreateUser").hide();
- $("#EditUser").show();
-
-
-
-
- $("#NameEdit").val(data.Name);
- $("#AddressEdit").val(data.Address);
- $("#PhoneNumberEdit").val(data.Phone_Number);
- $("#IdEdit").val(data.Id);
- }
- });
- }
-
-
- $("#btnSaveEdit").click(function(){
- var objUser={};
- objUser.Id= $("#IdEdit").val();
- objUser.Name = $("#NameEdit").val();
- objUser.Address = $("#AddressEdit").val();
- objUser.Phone_Number = $("#PhoneNumberEdit").val();
- $.post("/Users/EditUserJ", { objUser: objUser }, function (data)
- {
- if (data != null) {
- location.reload();
- alert("User Edited");
- }
- else {
- alert("Error");
- }
- });
- })
Now, add another method to Controller, as shown below.
- [HttpGet]
- public JsonResult EditUserJ(int Id)
- {
- try
- {
- using (JsonContext context = new JsonContext())
- {
- var User = context.ObjUser.Find(Id);
- if (User != null)
- {
- return Json(User, JsonRequestBehavior.AllowGet);
- }
- return Json(null, JsonRequestBehavior.AllowGet);
- }
- }
- catch (Exception ex)
- {
- return null;
- }
- }
- [HttpPost]
- public JsonResult EditUserJ(Users objUser)
- {
- try
- {
- using (JsonContext context = new JsonContext())
- {
- context.ObjUser.AddOrUpdate(objUser);
- context.SaveChanges();
- return Json(objUser, JsonRequestBehavior.AllowGet);
- }
- }
- catch (Exception ex)
- {
- return null;
- }
- }
For showing the details of the selected user, update the View page.
- <div class="form-horizontal" id="EditUser"></div>
-
-
- <div id="UserDetails">
- <h4>User</h4>
- <hr />
- <dl class="dl-horizontal">
- <dt>
- <input type="hidden" id="IdDetails" name="IdDetails" />
- <label id="">Name</label>
- </dt>
-
- <dd>
- <label id="NameDetails"></label>
- </dd>
-
- <dt>
- <label id="">Address</label>
- </dt>
-
- <dd>
- <label id="AddressDetails"></label>
- </dd>
-
- <dt>
- <label id="">Phone Number</label>
- </dt>
-
- <dd>
- <label id="PhoneNumberDetails"></label>
- </dd>
-
- </dl>
- </div>
Now, add the JavaScript.
- function Details(Id)
- {
- $.get("/Users/GetDetails",{Id:Id},function(data){
- if(data!=null)
- {
- $("#tableUser").hide();
- $("#CreateUser").hide();
- $("#EditUser").hide();
- $("#UserDetails").hide();
- $("#btnEditDetail").show();
-
-
-
- $("#NameDetails").text(data.Name);
- $("#AddressDetails").text(data.Address);
- $("#PhoneNumberDetails").text(data.Phone_Number);
- $("#IdDetails").text(data.Id);
- }
- });
- }
-
- $("#btnEditDetail").click(function(){
- var Id =document.getElementById("IdDetails").textContent;
- EditUser(Id);
- })
Add the methods to the Controller.
- public JsonResult GetDetails(int Id)
- {
- try
- {
- using (JsonContext context = new JsonContext())
- {
- var User = context.ObjUser.Find(Id);
- if (User != null)
- {
- return Json(User, JsonRequestBehavior.AllowGet);
- }
- return null;
- }
- }
- catch (Exception ex)
- {
- return null;
- }
- }
And now, for deleting Data(Users), add the following JavaScript function.
- function Delete(Id)
- {
- $.post("/Users/DeleteUserJ", { Id: Id }, function (data) {
- if (data != null) {
- location.reload();
- alert("User Deleted");
- }
- else {
- alert("Error");
- }
- });
- }
- [HttpPost]
- public JsonResult DeleteUserJ(int Id)
- {
- try
- {
- using (JsonContext context = new JsonContext())
- {
- var User = context.ObjUser.Find(Id);
- if (User != null)
- {
- context.ObjUser.Remove(User);
- context.SaveChanges();
- return Json(User, JsonRequestBehavior.AllowGet);
- }
- return Json(null, JsonRequestBehavior.AllowGet);
- }
- }
-
- catch (Exception ex)
- {
- return null;
- }
- }
That's it. Your CRUD operation will be done in the same page without any page load.