Monday, January 15, 2018

Asp.net mvc with jquery reuserble model dialog for adding reference data (e.g. Employee type, Termination Type)




In production normally used lot of master data with separate user interface for adding them. As an example if user goes to edit the employee with remarks which is a dropdown to select the particular remark of the control. What if the suggested remarks isn’t in the controller then user has to go the particular screen to add the remark and then has to refresh the current page for getting updated remarks.
In the above case what if it’s there any option for adding remark to the control itself without refreshing the page. As a common solution we can give common reusable interface for adding remark or whatever in to the control with adding few properties.
What we have to it just double click the dropdown and add items and it will updated the database and control itself with new data.

<select id="cmbResignReasonCategory"
class=" addDropDown"
data-NatTableName="hrm.ResignReasonCategory"
data-NatColName="ResignReasonCategoryName">
</select>

 Explanation
·         class=" addDropDown"
                This is the key class for fire the double click event in the control
·         data-NatTableName="hrm.ResignReasonCategory"
this is html5 data attribute for getting table name which is used to populate the dropdown

·         data-NatColName="ResignReasonCategoryName
o   This the table column name which is related to the table.

This is the only configuration is needed for getting this feature.

Technical Explanation:
The entire idea is very simple, when double click the control it is triggered the event which is used the following java script.

    <script>
    var NatDropDownAdd = function () {
        this.NatTableName = '';
        this.NatColName = '';
        this.NatValue = '';
        this.NatSavedID = 0;

    }

    var optionModl = function () {
        this.text = '';
    }
 
    $(document).ready(function (e) {
        $(document).on("dblclick", ".addDropDown", function (ee) {

            debugger;

            $("#CustomAddItem").modal();
            $("#NatSave").removeAttr("data-NatControlID");
            $("#NatSave").attr("data-NatControlID", $(this).attr('id'));
            var name = [];
            var input = $("#" + $(this).attr('id')).find("option").each(function (i) {
                debugger;
                if ($(this).val() != '0') {
                    var obj = new optionModl();
                    obj.text = $(this).text();
                    name.push(obj);
                }
            });
            $("#NatGet").html('');
            $("#NatGet").append(BindTable(name));

        });

        $(document).on("click", ".NatSave", function (ee) {
            debugger;
            var obj = new NatDropDownAdd();

            var natID = $(this).attr('data-NatControlID');

            obj.NatTableName = $('#' + natID).attr('data-NatTableName');
            obj.NatColName = $('#' + natID).attr('data-NatColName');
            obj.NatValue = $('#txtAddDropDownItem').val();

            if (obj.NatValue.length > 0) {
                ajaxCall('Testing/SavedDropDownItemAdd', { obj: obj }, function (obj) {
                    debugger;
                    $('#' + natID).append("<option value=" + obj.NatSavedID + " selected='selected'>" + obj.NatValue + "</option>");
                    $('#txtAddDropDownItem').val('');
                    $("#CustomAddItem .close").click()
                });
            }
            else {
                showMessage("Invalid value", "W");
            }
        });


function ajaxCall(url, parameters, successCallback) {
    //show loading... image
    //
 
    $.ajax({
        type: 'POST',
        url: rootUrl + url,
        timeout: 0,
        data: JSON.stringify(parameters),
        contentType: 'application/json;',
        dataType: 'json',
        success: successCallback,
        error: function (request, status, error) {
           
            console.log(request.responseText);
         
        } });
}

function BindTable(lst){

    var tbl = "<table id='x' class='table   table-striped table-bordered table-condensed bindTableSort tablesorters' >";
 
    //table header
    if (lst.length > 0) {
        tbl += "<thead> <tr style='font-weight:bold'>"
        tbl += "<th style='font-size: 12px !important;font-weight: bold !important;background-color: #f1f1f1;padding: 5px !important '>" + "#"+ "</th>";
            for (var i = 0; i < Object.keys(lst[0]).length; i++) {
                tbl += "<th class='" + Object.keys(lst[0])[i] + "' style='font-size: 12px !important;font-weight: bold !important;background-color: #f1f1f1;padding: 5px !important '>" + Object.keys(lst[0])[i] + "</th>";
            }
            tbl += "</tr></thead>";


            tbl += "<body>  "
           
            for (var i = 0; i < lst.length; i++) {
                tbl += "<tr>";
                tbl += "<td> " + (i + 1) + "</td>";
                for (var j = 0; j < Object.keys(lst[i]).length; j++) {
                    tbl += "<td class='" + Object.keys(lst[i])[j] + "'>" + lst[i][Object.keys(lst[i])[j]] + "</td>";
                }
                tbl += "</tr>";
            }
            tbl += " </body>";
    }
    tbl += "</table>"
    $('.bindTableSort').trigger('update');
    return tbl;
}

    });

    </script>
========================================================================


Model popup
    <div class="modal fade" id="CustomAddItem" role="dialog">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Add Dropdown Item</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group row">
                        <label class="control-label col-lg-2 col-md-2 col-sm-2" for="email">Value:</label>
                        <div class="col-lg-10  col-md-10 col-sm-10">
                            <div class="input-group">
                                <input type="text" class="form-control tab1 input-sm" id="txtAddDropDownItem" />
                                <span class="input-group-btn">
                                    <button type="button" id="NatSave" class="btn btn-primary input-sm NatSave">
                                        Save
                                    </button>
                                </span>
                            </div>

                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-lg-12 col-md-12 col-sm-12">
                            <div id="NatGet"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

========================================================================
Serverside

  [HttpPost]
        public JsonResult SavedDropDownItemAdd(NatDropDownModel obj)
        {

            string s=" Insert into " + obj.NatTableName + "  (" + obj.NatColName + ",EnteredBy,EnteredOn) values('" + obj.NatValue.ToUpper() + "'"    ); SELECT CAST(scope_identity() AS int)";
            int newID;
            using (SqlConnection con = new SqlConnection("YOURCONNECTIONSTRING"))
            {
                 using (SqlCommand insertCommand = new SqlCommand(s, con))
                {
                    con.Open();
                    newID = (int)insertCommand.ExecuteScalar();

                    if (con.State == System.Data.ConnectionState.Open) con.Close();
                 
                }
            }
            obj.NatSavedID = newID;
            return Json(obj, JsonRequestBehavior.AllowGet);



        }
========================================================================
Database Table

CREATE TABLE [HRM].[ResignReasonCategory](
[ResignReasonCategoryID] [smallint] IDENTITY(1,1) NOT NULL,
[ResignReasonCategoryName] [varchar](100) NULL

 CONSTRAINT [PK_ResignReasonCategory] PRIMARY KEY CLUSTERED
(
[ResignReasonCategoryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]


 ========================================================================

Add these file into the _Layout page.
That’s all