Thursday, 7 January 2016

Working with JSON using Json.NET by Newtonsoft 3 (Passing data from form to the server using JSON and JQuery and accessing via C# action)

Sometimes when we have a single page application or semi single page application, we have to pass data to the server without reloading the page.
For this purpose, we can use JQuery, JSON and a simple view in ASP.NET MVC.


First lets create a view with some validation

<!-- this is a button to show create employee modal -->
<button class="btn btn-primary" onclick="return createEmployeeShowModal()">
    Create New Employee
</button>

<!-- this is the create employee modal-->
<div class="modal fade" id="createEmployeeDialog" tabindex="-1" role="dialog" aria-labelledby="createEmployeeDialogLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="createEmployeeDialogLabel">Create New Employee</h4>
            </div>
            <input id="selectedDelete" type="hidden" value="-1" />
            <div class="modal-body">
                <div class="panel panel-body">
                    <div id="errorDiv" name="errorDiv" style="text-align:center; color:red">
                    </div>
                    <form>
                        <p>
                            <label for="firstName" class="control-label">First Name : </label>
                            <input type="text" id="firstName" name="firstName" class="form-control" />
                        </p>
                        <p>
                            <label for="middleName" class="control-label">Middle Name : </label>
                            <input type="text" id="middleName" name="middleName" class="form-control" />
                        </p>
                        <p>
                            <label for="lastName" class="control-label">Last Name : </label>
                            <input type="text" id="lastName" name="lastName" class="form-control" />
                        </p>
                        <p>
                            <label for="departmentSelect">Department : </label>
                            <select id="departmentSelect" name="departmentSelect" class="form-control"></select>
                        </p>
                        <p>
                            <label for="dateofBirth">Date of Birth (Use DD-MM-YYYY format) : </label>
                            <input type="text" id="dateofBirth" name="dateofBirth" class="form-control" />
                        </p>
                        <br />
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button onclick="return validateEmployee()" class="btn btn-primary">Add New Employee</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal">No</button>
            </div>
        </div>
    </div>
</div>


<!-- this is the create employee confirmation modal-->
<div class="modal fade" id="createEmployeeConfirmDialog" tabindex="-1" role="dialog" aria-labelledby="createEmployeeConfirmDialogLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="createEmployeeConfirmDialogLabel">Confirmation</h4>
            </div>
            <div class="modal-body">
                Are you sure you want to create this employee ?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="addNewEmployee()">Yes</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
            </div>
        </div>
    </div>
</div>


In the JavaScript add the following

//show the create employee modal
function createEmployeeShowModal() {
    $('#createEmployeeDialog').modal('show');
}



//validate employee
function validateEmployee() {

    var errorText = "";
    var hasErrors = false;

    var firstName = $("#firstName").val();
    var middleName = $("#middleName").val();
    var lastName = $("#lastName").val();
    var dateofBirth = $("#dateofBirth").val();
    var departmentID = $("#departmentSelect").val();

    if (firstName.trim() === "") {
        errorText = errorText + "<br/>First Name cannot be empty"
        hasErrors = true;
    }

    if (lastName.trim() === "") {
        errorText = errorText + "<br/>Last Name cannot be empty"
        hasErrors = true;
    }

    if (dateofBirth.trim() === "") {
        errorText = errorText + "<br/>Date of birth cannot be empty"
        hasErrors = true;
    } else if (dateofBirth.trim().length != 10) {
        errorText = errorText + "<br/>Incorrect date format"
        hasErrors = true;
    }
    else if ((dateofBirth.trim().split("-").length - 1) != 2) {
        errorText = errorText + "<br/>Incorrect date format"
        hasErrors = true;
    }

    if (hasErrors == true) {
        $('#errorDiv').html("<b>" + errorText + "</b><br/><br/>");
        $('#errorDiv').show();
        return false;
    }
    else {
        $('#errorDiv').html("");
        $('#errorDiv').hide();
        $('#createEmployeeConfirmDialog').modal('show');
    }

    return false;
}

//adding the employee (posting data to the server(Note the data part here)
function addNewEmployee() {
    var firstName = $("#firstName").val();
    var middleName = $("#middleName").val();
    var lastName = $("#lastName").val();
    var dateofBirth = $("#dateofBirth").val();
    var departmentID = $("#departmentSelect").val();


    var url = '/Home/AddNewEmployeeJSON';
    var data = {
        FirstName: firstName,
        MiddleName: middleName,
        LastName: lastName,
        DateofBirth: dateofBirth,
        DepartmentID: departmentID
    };

    $.post(
        url,
        data,
        function (result) {
            if (!$.isEmptyObject(result)) {
                if (result.errorCode === 1) {
                    location.assign('/Home/Retrieve');
                }
                else {
                    //there are errors
                    alert("faliure");
                }
            }
            else {
                alert("Unexpected Error, Returned Result is Empty.");
            }
        });

    return false;
}

//heres the code inside server /Home/AddNewEmployeeJSON

        public ActionResult AddNewEmployeeJSON(FormCollection fc)
        {      
            string firstName = fc["firstName"];
            string middleName = fc["middleName"];
            string lastName = fc["lastName"];
            string dateofBirth = fc["dateofBirth"];
            int departmentID = Convert.ToInt32(fc["departmentID"]);

//send data to BLL to create employee...
            int retVal = new BLLEmployeeManager().addNewEmployee(firstName, middleName, lastName, departmentID, dateofBirth);
            var camelCaseFormatter = new JsonSerializerSettings();
            camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();

            var jsonResult = new ContentResult
            {
                Content = JsonConvert.SerializeObject(
                new { errorCode = 1 }
                ,
                camelCaseFormatter
                ),
                ContentType = "application/json"
            };

            return jsonResult;
        }






Tuesday, 5 January 2016

Working with JSON using Json.NET by Newtonsoft 2 (Consume JSON with JQuery)

In the previous example, we discussed about how to return JSON with the use of JSON.NET.
Here, we consume the returned data and display it in the view, using JQuery.

In JQuery, there are 3 main ways to make ajax calls.

$.ajax();
$.get();
$.post();

In this tutorial, lets add some code to consume the JSON from the previous tutorial

since we want to show the data when the page loads, lets put the call inside the document.ready function

** please note that, I have 2 buttons inside this table with onclick functions they will open up modal dialogues to do relevant actions.
** for the 2 buttons, on the onClick methods, I pass in the relevant employeeID and with that, I am able to edit a particular employee...
**note that the table body in the view has a tbody with the id="tbodyEmp", which is used to append data into

Table in the view

      <div style="text-align:center">
         <table style="width:100%" class="table table-striped table-responsive table-bordered">
                        <tr>
                            <th>Employee ID</th>
                            <th>Employee Name</th>
                            <th>Edit Employee</th>
                            <th>Delete Employee</th>
                        </tr>  
                        <tbody id="tbodyEmp">
                        </tbody>                

            </table>
         </div>


Calling from the Javascript

$(document).ready(function () {
    //load employees
    var url = '/Home/GetAllEmployeesJSON';
 
//when we execute the ajax call, the script will continue to execute without waiting for the data
//to return, this will stop that
$.ajaxSetup({ async: false });

    $.post(
    url,
    function (result) {
        if (!$.isEmptyObject(result)) {
            var empListCount = result.length;
            for (var i = 0; i < empListCount; i++) {
                $("#tbodyEmp").append(
                            "<tr>" +
                                "<td>" + result[i].employeeID + "</td>" +
                                "<td>" + result[i].employeeName + "</td>" +
                                "<td>" +
                                    "<button onclick='return showEditEmployee(" + result[i].employeeID + ")'>" +
                                        "Edit" +
                                    "</button>" +
                                "</td>" +
                                "<td>" +
                                    "<button onclick='return showDeleteEmployee(" + result[i].employeeID + ")'>" +
                                        "Delete" +
                                    "</button>" +
                                "</td>" +
                            "</tr>"
                    );
            }
        }
        else {
            $('#empDisplayDiv').append(
                    "<div>Employee list not available</div>"
                );
        }
    });


    $.ajaxSetup({ async: true});   //this will resume the async....
});


//delete employee modal show
function showDeleteEmployee(empID) {
    $('#selectedDelete').val(empID);//this is how you assign a value using id
    $('#deleteEmployeeConfirmDialog').modal('show');
    return false;
}

delete employee modal in the view
<div class="modal fade" id="deleteEmployeeConfirmDialog" tabindex="-1" role="dialog" aria-labelledby="deleteEmployeeConfirmDialogLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="deleteEmployeeConfirmDialogLabel">Confirmation</h4>
            </div>
            <input id="selectedDelete" type="hidden" value="-1"/>
            <div class="modal-body">
                Are you sure you want to delete this employee ?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="deleteEmployee()">Yes</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
            </div>
        </div>
    </div>
</div>




//edit employee modal show
function showEditEmployee(empID) {
    $('#editEmployeeDialog').modal('show');

  //this is how you get values using id
   //var firstName = $("#editFirstName").val();

}

edit employee dialog
<div class="modal fade" id="editEmployeeDialog" tabindex="-1" role="dialog" aria-labelledby="editEmployeeDialogLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="editEmployeeDialogLabel">Edit Employee</h4>
            </div>
            <input id="selectedDelete" type="hidden" value="-1" />
            <div class="modal-body">
                <div class="panel panel-body">
                    <div id="editErrorDiv" name="editErrorDiv" style="text-align:center; color:red">
                    </div>
                    <form>
                        <p>
                            <label for="editFirstName" class="control-label">First Name : </label>
                            <input type="text" id="editFirstName" name="editFirstName" class="form-control" />
                        </p>
                        <p>
                            <label for="editMiddleName" class="control-label">Middle Name : </label>
                            <input type="text" id="editMiddleName" name="editMiddleName" class="form-control" />
                        </p>
                        <p>
                            <label for="editLastName" class="control-label">Last Name : </label>
                            <input type="text" id="editLastName" name="editLastName" class="form-control" />
                        </p>
                        <p>
                            <label for="editDepartmentSelect">Department : </label>
                            <select id="editDepartmentSelect" name="editDepartmentSelect" class="form-control"></select>
                        </p>
                        <p>
                            <label for="editDateofBirth">Date of Birth (Use DD-MM-YYYY format) : </label>
                            <input type="text" id="editDateofBirth" name="editDateofBirth" class="form-control" />
                        </p>
                        <input type="hidden" id="editCurrentID" value="-1"/>
                        <br />
                    </form>
                </div>
            </div>
            <div class="modal-footer">              
                <button onclick="return editValidateEmployee()" class="btn btn-primary">Edit Employee</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal">No</button>
            </div>
        </div>
    </div>
</div>



Sunday, 3 January 2016

Working with JSON using Json.NET by Newtonsoft 1 (Returning JSON)

In ASP.NET MVC application development, controller actions can be used to return content.
When you go in to a particular url, you will be pointed to a view (most of the time).

With Newtonsoft's JSON.NET, those urls can be used to retrieve JSON.

Before we start, you should create a simple MVC application, in that application,
right click and go to the nuget package manager (right click -> manage nuget packages).

in there search for 
Newtonsoft.Json

install it to your application.

in order for us to use the JSON.NET, we have to import the following in to our code (here I am putting them in the controller)

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;


now that we have the relevant imports, lets see some sample code to return json,

use the following code to make the relevant JSON comply with the camel case notation

var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();

now lets create a ContentResult object that we can return.

            var jsonResult = new ContentResult
            {
                Content = JsonConvert.SerializeObject(
               <<this will have the returning object>>
                ,
                camelCaseFormatter
                ),
                ContentType = "application/json"
            };

            return jsonResult;



Heres a complete example.

in models we can create,

    public class EmployeeDisplayModel
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
    }

in the controller add the following action

public class HomeController : Controller
{

        public ActionResult GetAllEmployeesJSON()
        {
            List<EmployeeDisplayModel> empDisplayList = new List<EmployeeDisplayModel>();
            empDisplayList.Add(new EmployeeDisplayModel() {
                EmployeeID = 1,
                EmployeeName = "emp1"
            });
            empDisplayList.Add(new EmployeeDisplayModel()
            {
                EmployeeID = 2,
                EmployeeName = "emp2"
            });
            empDisplayList.Add(new EmployeeDisplayModel()
            {
                EmployeeID = 3,
                EmployeeName = "emp3"
            });

            var camelCaseFormatter = new JsonSerializerSettings();
   camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();

            var jsonResult = new ContentResult
            {
                Content = JsonConvert.SerializeObject(
                empDisplayList
                ,
                camelCaseFormatter
                ),
                ContentType = "application/json"
            };

            return jsonResult;
         }
}


when you can access them by going to the relavent /<<controller>>/<<action>> link,