Friday, December 4, 2015

Passing form to Controller with AJAX Call

Passing form to C# MVC4 Controller with AJAX Call 

The HTML Form with easy ui , C# , MVC4


 <form id="frmAttendance">
                    <div class="fitem">
                        <label>Section:</label>
                        <input name="SrcSectionCodef" id="SrcSectionCodef" class="easyui-combobox" data-options="panelHeight:'auto', width:250, required:true,onSelect:popEmployee2">
                    </div>
                    <div class="fitem">
                        <label>Employee:</label>
                        <input id="strSAPIDf" name="strSAPIDf" type="text" class="easyui-combogrid" data-options="panelWidth:450, width:225,
                                                                                                                          editable:true,
                                                                                                                          idField: 'SAP_Code',
                                                                                                                          textField: 'EmplName',
                                                                                                                          columns: [[
                                                                                                                                    {field:'SAP_Code',title:'SAP Code',width:50},
                                                                                                                                    {field:'EmplName',title:'Employee Name',width:180},
                                                                                                                                    {field:'Level',title:'Empl Level',width:80,align:'right'},
                                                                                                                                   ]],
                                                                                                                                   fitColumns:true,
                                                                                                                                   required: true" />
                    </div>
                    <div class="fitem">
                        <label>Date :</label>
                        <input id="dateAtf" name="dateAtf" type="text" class="easyui-datetimebox" data-options="width:150,required: true">
                    </div>
                    <div class="fitem">
                        <label>In / out:</label>
                        <select class="easyui-combobox" name="inoutf" id="inoutf" style="width:140px" data-options="panelHeight:50,required: true">
                            <option value="A">in</option>
                            <option value="D">out</option>
                        </select>
                    </div>
                   </form>


The Ajax Call (javascript function)


 function saveAttendance() {

        showProgress('show');
        var postDataa = $('#frmAttendance').serializeObject();
        $('#dbGridGroup').datagrid({ data: [] });
        $.ajax({
            url: '/Attendance/AttendanceSave',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(postDataa),
            success: function (result) {
                if (!result) {
                    showProgress('hide');
                    $.messager.alert(appsTitle, 'No data found, please try again', 'info');
                    return;
                }
                if (result.length == 0) {
                    showProgress('hide');
                    $.messager.alert(appsTitle, 'No data found, please try again', 'info');
                    return;
                }

                $('#dbGridGroup').datagrid({ data: result });
                $('#dlg').dialog('close');
                showProgress('hide');
            },
            error: function () {
                $.messager.alert(appsTitle, 'Unknown error', 'info');
                showProgress('hide');
                return;
            }
        });
    }

The Controller (URL :/Attendance/AttendanceSave


public JsonResult AttendanceSave(string SrcSectionCodef, string strSAPIDf, string dateAtf, string inoutf)
        {
            Attendance att = new Attendance();
            string bln = dateAtf.Split(' ')[0].Split('/')[0];
            string tgl = dateAtf.Split(' ')[0].Split('/')[1];
            string tahun = dateAtf.Split(' ')[0].Split('/')[2];
            string datTRX = tahun + "-" + bln + "-" + tgl;
            UserLogin userlogin = (UserLogin)Session["userLogin"];
            att.strFileName = "manual input";
            att.strLineText = "manual input" + strSAPIDf;
            att.strTerminal = "999";
            att.strSAPID = "0" + strSAPIDf;
            att.strTime = dateAtf.Split(' ')[1].Split(':')[0+ "" + dateAtf.Split(' ')[1].Split(':')[1];
            att.strDate = bln + "" + tgl;
            att.strStatus = inoutf;
            att.DatTrxDate = Convert.ToDateTime(dateAtf);
            att.strSAPLineText = att.strTerminal + "" + att.strSAPID + "" + att.strTime + "" + att.strDate + "" + att.strStatus;
            att.CreatedBy = att.UpdatedBy = userlogin.UserLoginId;
            att.CreatedDate = att.UpdatedDate = DateTime.Now;
            AttendanceCRUD.AttendanceSave(att);
            List<Attendance> List = AttendanceCRUD.GetEmployeAttendance(att.strSAPID, att.strDate, datTRX);
            return Json(List);
        }

Explanation: 

Before we start just to make sure id in the form should be have same name like variable name that we use in Controller to passing the value of the form , so our program know how to mapping the value from the form to controller, okay.

Now for the Ajax Call
We start with $(‘#Form_Id’).SerializeObject();
In Ajax, set The url to Controller/(Procedure/function) , type : POST, and don’t forget set contentType to ‘Application/json’, at data we should stringify the form by data: JSON.stringify(Formvalue).

$('#dbGridGroup').datagrid({ data: [] });
  If you have question what is that line for, I use that to set empty my datagrid.
The re-set it after save procedure completed by 
$('#dbGridGroup').datagrid({ data: result });


No comments:

Post a Comment