Click here to Skip to main content
15,886,199 members
Articles / Web Development / ASP.NET / ASP.NET4.0

CRUD in single View using Javascript in MVC and Searching Using Json File

Rate me:
Please Sign up or sign in to vote.
4.85/5 (7 votes)
11 Aug 2016CPOL2 min read 17.8K   5  
This artcile shows how to make a CRUD operation in single View using Javascript in MVC

Introduction

This artcile shows how to make a CRUD operation in single View using Javascript in MVC and searching data(Filteration) from the Json file.

Start

This article covers how to make a CRUD (Create, Edit , Update , Delete, Details) operation in a single view(page) using javascript and Ajax calls in MVC. And also how to create Json File and filteration(Searching) data from json file.

Also I am using Entity Framework for this sample project.

So create and Asp.Net project.Follow the Following Steps

  1. Open Visual Studio.Select New Project.
  2. In Visual C# tab select Asp.Net web application.
  3. Now Select an Empty Project. And in "Add folders and core reference for:" section select MVC. And select OK.
  4. Now Right Click on your Solution and another Project as a Class Library (as i am using Entity Framework).
  5. Add a Class in that Class Library as below

 

C#
 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 below.

 

C#
 public class JsonContext:DbContext
    {
        public DbSet<Users> ObjUser { get; set; }
    }

Now in Web.Config file of Project add the following Connection string.

HTML
<connectionStrings>
    <add name="JsonContext" connectionString="Provide your credentials" providerName="System.Data.SqlClient" />
  </connectionStrings>

Now add the Class library in a reference of your Project.And build the Solution.

Add the Empty Controller.In controllers folder of the Project.

Add the following ActionResult Method to your Controller

C#
   public ActionResult Index()
        {
            using (JsonContext context = new JsonContext())
            {              
                    return View(context.ObjUser.ToList());        //This will get the list of all users present in db
            }
        }

Now in the view of the Index method 

for displaying the list of the user in a table with edit,delete and details option for each.

HTML
@model IEnumerable<JsonEntity.Users>  //JsonEntity is my Class Library Name and Users is my Class name 

@{
    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" /> |  //EditUser is a javascript function and passing Selected users id to the function
            <input type="button" id="btnDetailUser" value="Details" onclick="Details(@item.Id)" class="btn btn-default" /> |   //Details is a javascript function
            <input type="button" id="btnDeleteUser" value="Delete" onclick="Delete(@item.Id)" class="btn btn-default" />       //Delete is a javascript function               
        </td>
    </tr>
}

</table>

Here your users list would be empty.

To create a user update your view as following.

HTML
@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 adding a Javascript to create a User.

HTML
<script type="text/javascript">
$("#btnCreate").click(function () {
        var objUser = {};                   //objUser is variable through which i am passing the details filled by the user to the controller
        objUser.Name = $("#Name").val();            //fetching value from the textbox
        objUser.Address = $("#Address").val();
        objUser.Phone_Number = $("#PhoneNumber").val();
        $.post("/Users/CreateUser", { objUser: objUser }, function (data)        //data is a variable which contains the data returned from the action method
        {
            if (data != null) {                
                alert("User Created");
                location.reload();       //for refreshing the page after saving 
            }
            else {
                alert("Error");
            }
        });
    })
 </script>

Add a JsonResult method in your Controller.

C#
  [HttpPost]
        public JsonResult CreateUser(Users objUser)         //objUser is object which should be same as in javascript function
        {
            try
            {
                using (JsonContext context = new JsonContext())
                {
                    context.ObjUser.Add(objUser);
                    context.SaveChanges();
                    return Json(objUser, JsonRequestBehavior.AllowGet);        //returning user to javacript
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

Now for editing the Users update your Index view as below.

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

HTML
 function EditUser(Id)
    {       
        $.get("/Users/EditUserJ",{Id:Id},function(data){              //fetching data of the selected user from controller
            if(data!=null)
            {                
                    $("#tableUser").hide();
                    $("#CreateUser").hide();                   
                    $("#EditUser").show();

                    //data contains the details of the user 
                    // now showing those details in the textbox
 
                    $("#NameEdit").val(data.Name);
                    $("#AddressEdit").val(data.Address);
                    $("#PhoneNumberEdit").val(data.Phone_Number);     
                    $("#IdEdit").val(data.Id);
                }
        });
    }  


 $("#btnSaveEdit").click(function(){
        var objUser={};                      //same action as per creating the user
        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 below.

C#
  [HttpGet]
        public JsonResult EditUserJ(int Id)    //For getting details of the selected User
        {
            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)      //For Updating changes 
        {
            try
            {
                using (JsonContext context = new JsonContext())
                {
                    context.ObjUser.AddOrUpdate(objUser);
                    context.SaveChanges();
                    return Json(objUser, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

Now for Showing details of the selected user update the View page.

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

JavaScript
  function Details(Id)
    {
        $.get("/Users/GetDetails",{Id:Id},function(data){
            if(data!=null)
            {
                $("#tableUser").hide();
                $("#CreateUser").hide();
                $("#EditUser").hide();
                $("#UserDetails").hide();
                $("#btnEditDetail").show();

                //showing details from the data in the label

                $("#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

C#
  public JsonResult GetDetails(int Id)                       //fetching details of the selected user and passing to the javascript function
        {
            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 Javascript Function.

JavaScript
  function Delete(Id)
    {
        $.post("/Users/DeleteUserJ", { Id: Id }, function (data) {      //passing the id of the selected user to the action method for deletion
            if (data != null) {
                location.reload();
                alert("User Deleted");
            }
            else {
                alert("Error");
            }
        });
    }

Now add a method for deleting

C#
    [HttpPost]
        public JsonResult DeleteUserJ(int Id)
        {
            try
            {
                using (JsonContext context = new JsonContext())
                {
                    var User = context.ObjUser.Find(Id);         //fetching the user with Id 
                    if (User != null)
                    {
                        context.ObjUser.Remove(User);              //deleting from db
                        context.SaveChanges();
                        return Json(User, JsonRequestBehavior.AllowGet);
                    }
                    return Json(null, JsonRequestBehavior.AllowGet);
                }
            }

            catch (Exception ex)
            {
                return null;
            }
        }

Creating a Json File. Json file helps us to get data without interacting the Server.

Update your Index view page.

HTML
@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" />
   <input type="button" id="btnCreateJson" value="Create Json"  class="btn btn-default"/>   
    <input type="button" id="get-data" value="Get Data From json" class="btn btn-default" />
</p>

Now add another javascript

JavaScript
  $("#btnCreateJson").click(function () {
        $.post("/Users/CreateJson", function (response) {
            if (response != null) {              
                alert("Json Created");
                location.reload();
            }
            else {
                alert("Error");
            }
        });
    })

Add a method to controller.

C#
  [HttpPost]
        public ActionResult CreateJson()
        {
            try
            {
                using (JsonContext context = new JsonContext())
                {
                    var UsersList = context.ObjUser.ToList();             // Getting the list of users for DB.
                    var jsondata = new JavaScriptSerializer().Serialize(UsersList);
                    string path = Server.MapPath("~/Json/");             //Path where your json file will be saved
                    System.IO.File.WriteAllText(path + "User.json", jsondata);            // User.json is your json file's name
                    return Json(1);
                }
            }
            catch(Exception ez)
            {
                return Json(0);
            }
        }  

Now getting the list of user from Json File

Add another javascript

JavaScript
 $('#get-data').click(function () {           
            var url="/Json/User.json";
            $.getJSON(url, function (data) {   //this method gets the json file and fetches the data inside it
                console.log(data);             
                $('#show-data').empty();

                if (data.length) {
                    var content="<table class='table'>";
                    for(var i=0;i<data.length;i++)
                    {
                        content+="<tr><td>"+data[i].Name+"</td><td>"+data[i].Address+"</td><td>"+data[i].Phone_Number+"</td></tr>";                                              
                    }
                    content+="</table>";
                    $('#show-data').append(content);  //this is to append the data fetched from json to the table
                }
            });

            showData.text('Loading the JSON file.');
    })

Now searching data from Json File

HTML
@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" />
   <input type="button" id="btnCreateJson" value="Create Json"  class="btn btn-default"/>    
    <input type="text" id="Search"  placeholder="Enter data"/>
    <input type="button" id="get-data" value="Get Data From json" class="btn btn-default" />
</p>

Javascript :-

JavaScript
//here i had used keyup function as i want to filter data with the single alpha  matching  

 $("#Search").keyup(function (e) {
        clearTimeout($.data(this, 'timer'));
        if (e.keyCode == 13)
            DataFromJson(true);
        else
            $(this).data('timer', setTimeout(DataFromJson, 50));     //sets the timer for seraching
    })

    function DataFromJson(force)
    {        
        var event = $("#Search").val();        //fetching the value from the textbox
            var url = "/Json/User.json";
            $.getJSON(url, function (response) {
                //console.log(response);
                if (response.length) {
                    $("#tableUser").empty();
                    var content = "<tr><th>Name</th><th>Address</th><th>Phone Number</th></tr>";
                    for (var i = 0; i < response.length; i++) {
                        if ((response[i].Name).indexOf(event) != -1 || (response[i].Address).indexOf(event) != -1 || (response[i].Phone_Number).indexOf(event) != -1) {
                            content += "<tr id='TableData'><td>" + response[i].Name + "</td><td>" + response[i].Address + "</td><td>" + response[i].Phone_Number + "</td><td><input type='button' id='btnEditUser' value='Edit' class='btn btn-default' onclick='EditUser(" + response[i].Id + ")'/> | <input type='button' id='btnDetailUser' class='btn btn-default' value='Details' onclick='Details(" + response[i].Id + ")'/> | <input type='button' id='btnDeleteUser' value='Delete' onclick='Delete(" + response[i].Id + ")' class='btn btn-default'/></td></tr>";
                        }
                    }
                    $("#tableUser").append(content); //appending the list to the table
                }
            });        
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior) Inkswipe
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --