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;
        }






No comments:

Post a Comment