Creating CRUD In Single Page View

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

  1. Open Visual Studio. Select New Project.
  2. In Visual C# tab, select ASP.NET Web Application.
  3. Now, select an Empty Project. In "Add folders and core reference for:" section, select MVC and click OK.
  4. Now, right click on your Solution and add another Project as Class Library (as I am using Entity Framework).
  5. Add a Class in that Class Library, as shown below:
  1. public class Users  
  2.    {  
  3.        [Key]  
  4.        public int Id { getset; }  
  5.        public string Name { getset; }  
  6.        public string Address { getset; }  
  7.        public string Phone_Number { getset; }  
  8.    }  

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.

  1. public class JsonContext:DbContext  
  2.    {  
  3.        public DbSet<Users> ObjUser { getset; }  
  4.    }  

Now, in Web.Config file of Projectadd the following Connection string.

  1. <connectionStrings>  
  2.     <add name="JsonContext" connectionString="Provide your credentials" providerName="System.Data.SqlClient" />  
  3.   </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.

  1. public ActionResult Index()  
  2.        {  
  3.            using (JsonContext context = new JsonContext())  
  4.            {                
  5.                    return View(context.ObjUser.ToList());        //This will get the list of all users present in db  
  6.            }  
  7.        }  

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. 

  1. @model IEnumerable<JsonEntity.Users>  //JsonEntity is my Class Library Name and Users is my Class name   
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8.   
  9. <table id="tableUser" class="table">  
  10.     <tr>  
  11.         <th>  
  12.             @Html.DisplayNameFor(model => model.Name)  
  13.         </th>  
  14.         <th>  
  15.             @Html.DisplayNameFor(model => model.Address)  
  16.         </th>  
  17.         <th>  
  18.             @Html.DisplayNameFor(model => model.Phone_Number)  
  19.         </th>  
  20.         <th></th>  
  21.     </tr>  
  22.   
  23. @foreach (var item in Model) {  
  24.     <tr id="TableData">  
  25.         <td>  
  26.             @Html.DisplayFor(modelItem => item.Name)  
  27.         </td>  
  28.         <td>  
  29.             @Html.DisplayFor(modelItem => item.Address)  
  30.         </td>  
  31.         <td>  
  32.             @Html.DisplayFor(modelItem => item.Phone_Number)  
  33.         </td>  
  34.         <td>  
  35.             <input type="button" id="btnEditUser" value="Edit" onclick="EditUser(@item.Id)" class="btn btn-default" /> |  //EditUser is a javascript function and passing Selected users id to the function  
  36.             <input type="button" id="btnDetailUser" value="Details" onclick="Details(@item.Id)" class="btn btn-default" /> |   //Details is a javascript function  
  37.             <input type="button" id="btnDeleteUser" value="Delete" onclick="Delete(@item.Id)" class="btn btn-default" />       //Delete is a javascript function                 
  38.         </td>  
  39.     </tr>  
  40. }  
  41.   
  42. </table>   

Here, your users list would be empty. To create a user, update your View as the following.

  1. @model IEnumerable<JsonEntity.Users>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8. <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>  
  9. <p>     
  10.     <input type="button" id="btnCreateUser" value="Create User"  class="btn btn-default" />   
  11. </p>  
  12.   
  13.   
  14. <table id="tableUser" class="table"></table>  
  15.   
  16.   
  17. <div id="CreateUser" class="form-horizontal">  
  18.     <h4>Users</h4>  
  19.     <hr />  
  20.     @Html.ValidationSummary(true""new { @class = "text-danger" })  
  21.     <div class="form-group">  
  22.         <label class = "control-label col-md-2">Name</label>        
  23.         <div class="col-md-10">  
  24.             <input class="form-control" type="text" name="Name" id="Name"/>            
  25.         </div>  
  26.     </div>  
  27.   
  28.     <div class="form-group">  
  29.         <label class="control-label col-md-2">Address</label>       
  30.         <div class="col-md-10">  
  31.             <input class="form-control" type="text" name="Address" id="Address" />             
  32.         </div>  
  33.     </div>  
  34.   
  35.     <div class="form-group">         
  36.         <label class="control-label col-md-2">Phone Number</label>  
  37.         <div class="col-md-10">  
  38.             <input class="form-control" type="text" name="PhoneNumber" id="PhoneNumber" />             
  39.         </div>  
  40.     </div>  
  41.   
  42.     <div class="form-group">  
  43.         <div class="col-md-offset-2 col-md-10">  
  44.             <input type="button" id="btnCreate"value="Create" class="btn btn-default" />  
  45.             <input type="button" id="btnJson" value="Create Json"  class="btn btn-default" />  
  46.         </div>  
  47.     </div>  
  48. </div>  

Now, add a JavaScript to create a User.

  1. <script type="text/javascript">  
  2. $("#btnCreate").click(function () {  
  3.         var objUser = {};                   //objUser is variable through which i am passing the details filled by the user to the controller  
  4.         objUser.Name = $("#Name").val();            //fetching value from the textbox  
  5.         objUser.Address = $("#Address").val();  
  6.         objUser.Phone_Number = $("#PhoneNumber").val();  
  7.         $.post("/Users/CreateUser", { objUser: objUser }, function (data)        //data is a variable which contains the data returned from the action method  
  8.         {  
  9.             if (data != null) {                  
  10.                 alert("User Created");  
  11.                 location.reload();       //for refreshing the page after saving   
  12.             }  
  13.             else {  
  14.                 alert("Error");  
  15.             }  
  16.         });  
  17.     })  
  18.  </script>  
Add a JsonResult method in your Controller.
  1. [HttpPost]  
  2.         public JsonResult CreateUser(Users objUser)         //objUser is object which should be same as in javascript function  
  3.         {  
  4.             try  
  5.             {  
  6.                 using (JsonContext context = new JsonContext())  
  7.                 {  
  8.                     context.ObjUser.Add(objUser);  
  9.                     context.SaveChanges();  
  10.                     return Json(objUser, JsonRequestBehavior.AllowGet);        //returning user to javacript  
  11.                 }  
  12.             }  
  13.             catch (Exception ex)  
  14.             {  
  15.                 return null;  
  16.             }  
  17.         }  
Now, for editing the Users, update your Index View with the code shown below.
  1. <div id="CreateUser" class="form-horizontal"></div>  
  2.   
  3. <div class="form-horizontal" id="EditUser">  
  4.     <h4>Users</h4>  
  5.     <hr />  
  6.     @Html.ValidationSummary(true""new { @class = "text-danger" })    
  7.     <div class="form-group">  
  8.         <input type="hidden" id="IdEdit" name="IdEdit"/>  
  9.         <label class="control-label col-md-2">Name</label>         
  10.         <div class="col-md-10">  
  11.             <input class="form-control" type="text" name="NameEdit" id="NameEdit" />             
  12.         </div>  
  13.     </div>  
  14.   
  15.     <div class="form-group">  
  16.         <label class="control-label col-md-2">Address</label>       
  17.         <div class="col-md-10">  
  18.             <input class="form-control" type="text" name="AddressEdit" id="AddressEdit" />            
  19.         </div>  
  20.     </div>  
  21.   
  22.     <div class="form-group">        
  23.         <label class="control-label col-md-2">Phone Number</label>  
  24.         <div class="col-md-10">  
  25.             <input class="form-control" type="text" name="PhoneNumberEdit" id="PhoneNumberEdit" />            
  26.         </div>  
  27.     </div>  
  28.     <div class="form-group">  
  29.         <div class="col-md-offset-2 col-md-10">  
  30.             <input type="button" value="Save" id="btnSaveEdit" class="btn btn-default" />  
  31.         </div>  
  32.     </div>  
  33. </div>  
Add another JavaScript function in your View.
  1. function EditUser(Id)  
  2.     {         
  3.         $.get("/Users/EditUserJ",{Id:Id},function(data){              //fetching data of the selected user from controller  
  4.             if(data!=null)  
  5.             {                  
  6.                     $("#tableUser").hide();  
  7.                     $("#CreateUser").hide();                     
  8.                     $("#EditUser").show();  
  9.   
  10.                     //data contains the details of the user   
  11.                     // now showing those details in the textbox  
  12.    
  13.                     $("#NameEdit").val(data.Name);  
  14.                     $("#AddressEdit").val(data.Address);  
  15.                     $("#PhoneNumberEdit").val(data.Phone_Number);       
  16.                     $("#IdEdit").val(data.Id);  
  17.                 }  
  18.         });  
  19.     }    
  20.   
  21.   
  22.  $("#btnSaveEdit").click(function(){  
  23.         var objUser={};                      //same action as per creating the user  
  24.         objUser.Id= $("#IdEdit").val();  
  25.         objUser.Name = $("#NameEdit").val();  
  26.         objUser.Address = $("#AddressEdit").val();  
  27.         objUser.Phone_Number = $("#PhoneNumberEdit").val();  
  28.         $.post("/Users/EditUserJ", { objUser: objUser }, function (data)  
  29.         {  
  30.             if (data != null) {        
  31.                 location.reload();  
  32.                 alert("User Edited");  
  33.             }  
  34.             else {  
  35.                 alert("Error");  
  36.             }  
  37.         });  
  38.     })  
Now, add another method to Controller, as shown below.
  1. [HttpGet]  
  2.        public JsonResult EditUserJ(int Id)    //For getting details of the selected User  
  3.        {  
  4.            try  
  5.            {  
  6.                using (JsonContext context = new JsonContext())  
  7.                {  
  8.                    var User = context.ObjUser.Find(Id);  
  9.                    if (User != null)  
  10.                    {  
  11.                        return Json(User, JsonRequestBehavior.AllowGet);  
  12.                    }  
  13.                    return Json(null, JsonRequestBehavior.AllowGet);  
  14.                }  
  15.            }  
  16.            catch (Exception ex)  
  17.            {  
  18.                return null;  
  19.            }  
  20.        }  
  21.        [HttpPost]  
  22.        public JsonResult EditUserJ(Users objUser)      //For Updating changes   
  23.        {  
  24.            try  
  25.            {  
  26.                using (JsonContext context = new JsonContext())  
  27.                {  
  28.                    context.ObjUser.AddOrUpdate(objUser);  
  29.                    context.SaveChanges();  
  30.                    return Json(objUser, JsonRequestBehavior.AllowGet);  
  31.                }  
  32.            }  
  33.            catch (Exception ex)  
  34.            {  
  35.                return null;  
  36.            }  
  37.        }  

For showing the details of the selected user, update the View page.

  1. <div class="form-horizontal" id="EditUser"></div>  
  2.   
  3.   
  4. <div id="UserDetails">  
  5.     <h4>User</h4>  
  6.     <hr />  
  7.     <dl class="dl-horizontal">  
  8.         <dt>  
  9.             <input type="hidden" id="IdDetails" name="IdDetails" />  
  10.             <label id="">Name</label>              
  11.         </dt>  
  12.   
  13.         <dd>  
  14.             <label id="NameDetails"></label>             
  15.         </dd>  
  16.   
  17.         <dt>  
  18.             <label id="">Address</label>             
  19.         </dt>  
  20.   
  21.         <dd>  
  22.             <label id="AddressDetails"></label>            
  23.         </dd>  
  24.   
  25.         <dt>  
  26.             <label id="">Phone Number</label>             
  27.         </dt>  
  28.   
  29.         <dd>  
  30.             <label id="PhoneNumberDetails"></label>            
  31.         </dd>  
  32.   
  33.     </dl>  
  34. </div>  

Now, add the JavaScript.

  1. function Details(Id)  
  2.     {  
  3.         $.get("/Users/GetDetails",{Id:Id},function(data){  
  4.             if(data!=null)  
  5.             {  
  6.                 $("#tableUser").hide();  
  7.                 $("#CreateUser").hide();  
  8.                 $("#EditUser").hide();  
  9.                 $("#UserDetails").hide();  
  10.                 $("#btnEditDetail").show();  
  11.   
  12.                 //showing details from the data in the label  
  13.   
  14.                 $("#NameDetails").text(data.Name);  
  15.                 $("#AddressDetails").text(data.Address);  
  16.                 $("#PhoneNumberDetails").text(data.Phone_Number);     
  17.                 $("#IdDetails").text(data.Id);  
  18.             }  
  19.         });  
  20.     }  
  21.   
  22.  $("#btnEditDetail").click(function(){  
  23.         var Id =document.getElementById("IdDetails").textContent;          
  24.         EditUser(Id);  
  25.     })  

Add the methods to the Controller.

  1. public JsonResult GetDetails(int Id)                       //fetching details of the selected user and passing to the javascript function  
  2.       {  
  3.           try  
  4.           {  
  5.               using (JsonContext context = new JsonContext())  
  6.               {  
  7.                   var User = context.ObjUser.Find(Id);  
  8.                   if (User != null)  
  9.                   {  
  10.                       return Json(User, JsonRequestBehavior.AllowGet);  
  11.                   }  
  12.                   return null;  
  13.               }  
  14.           }  
  15.           catch (Exception ex)  
  16.           {  
  17.               return null;  
  18.           }  
  19.       }  

And now, for deleting Data(Users), add the following JavaScript function.

  1. function Delete(Id)  
  2.    {  
  3.        $.post("/Users/DeleteUserJ", { Id: Id }, function (data) {      //passing the id of the selected user to the action method for deletion  
  4.            if (data != null) {  
  5.                location.reload();  
  6.                alert("User Deleted");  
  7.            }  
  8.            else {  
  9.                alert("Error");  
  10.            }  
  11.        });  
  12.    }  
  1. [HttpPost]  
  2.        public JsonResult DeleteUserJ(int Id)  
  3.        {  
  4.            try  
  5.            {  
  6.                using (JsonContext context = new JsonContext())  
  7.                {  
  8.                    var User = context.ObjUser.Find(Id);         //fetching the user with Id   
  9.                    if (User != null)  
  10.                    {  
  11.                        context.ObjUser.Remove(User);              //deleting from db  
  12.                        context.SaveChanges();  
  13.                        return Json(User, JsonRequestBehavior.AllowGet);  
  14.                    }  
  15.                    return Json(null, JsonRequestBehavior.AllowGet);  
  16.                }  
  17.            }  
  18.   
  19.            catch (Exception ex)  
  20.            {  
  21.                return null;  
  22.            }  
  23.        }  
That's it. Your CRUD operation will be done in  the same page without any page load.


Similar Articles