I am trying to map a Ionic mobile app with a deployed web service.
I want to insert form data so that it can be updated in the database via a .NET asmx web service. the ajax code is as follows:
$.ajax({
url: 'http://localhost:5096/AndroidWebService.asmx/InsrtTblEmp', type: "POST",
contentType: "application/json",
data: //what to do here?,
dataType: "json",
success: function (result) {
var jEl = $("#divMessage");
jEl.html(result.d).fadeIn(1000);
setTimeout(function () { jEl.fadeOut(1000) }, 5000);
},
error: function (xhr, status) {
alert("An error occurred: " + status);
}
});
here is the code for the asmx web service:
[WebMethod]
//public string InsrtTblEmp(int EmpId, string LeaveType, DateTime DateFrom, DateTime DateTo, float? LeaveDays, string Remarks)
public string InsrtTblEmp(TblEmpLeaveDat TblEmpDat)
{
string msg ="";
try
{
var obj = new tblEmpLeave()
{
EmpId = TblEmpDat.EmpId,
LeaveAvailType = TblEmpDat.LeaveAvailType,
DateFrom = TblEmpDat.DateFrom,
DateTo = TblEmpDat.DateTo,
LeaveDays = TblEmpDat.LeaveDays,
Remarks = TblEmpDat.Remarks
};
Db.tblEmpLeaves.Add(obj);
Db.SaveChanges();
msg = "Record insert successfully";
}
catch(Exception ex)
{
msg = ex.Message;
}
return msg;
}
}
Now from what i understand, the web service is only accepting an object datatype. first question: can i create objects in jquery?
will it be more efficient to use this web service as it is? or should i modify it so that it takes hard coded string values rather than the object.
Any help would be appreciated.
If the names of the fields in your form are the same as they are in your model, you can do this:
var frm = $(document.myform);
var formData = JSON.stringify(frm.serializeArray());
$.ajax({
url: 'http://localhost:5096/AndroidWebService.asmx/InsrtTblEmp',
type: "POST",
contentType: "application/json",
data: formData,
dataType: "json",
success: function (result) {
var jEl = $("#divMessage");
jEl.html(result.d).fadeIn(1000);
setTimeout(function () { jEl.fadeOut(1000) }, 5000);
},
error: function (xhr, status) {
alert("An error occurred: " + status);
}
});
If the form names are different, you set the data in formData like this:
var formData= {
EmpId: $('.input1').val(),
LeaveAvailType: $('.input2').val(),
DateFrom: $('.input3').val(),
DateTo: $('.input4').val(),
LeaveDays: $('.input5').val(),
Remarks: $('.input6').val()
};