Call WebMethod using jQuery - c#

Hi i want to pass the values from jQuery and assign those values to a class model which is used in a method.
Following is my script:
$(document).ready(function(){
$('#BtnSubmit').click(function () {
var CollegeName = $('#TxtCollegeName').val();
var CollegeAddress = $('#TxtCollegeAddress').val();
var pageUrl = '<%=ResolveUrl("~/AddNewCollege.aspx/CreateCollegeData")%>';
$.ajax({
type: 'Post',
url: pageUrl,
data: JSON.stringify({ "CollegeName": CollegeName, "CollegeAddress": CollegeAddress}),
dataType: 'text',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblResult').html('Inserted Successfully');
},
error: function () {
alert("An error occurred.");
}
});
});
});
Below is my Csharp method:
[WebMethod]
public static string CreateCollegeData(CollegeDetails collegeDetails)
{
CollegeDAL obj = new CollegeDAL();
bool b = obj.InsertCollegeDetails(collegeDetails);
return "success";
}
But debugger is unable to call the web method. Every time the following message is coming:

Try declaring your object ahead of time: link

I got another solution.
$('#BtnSubmit').click(function () {
var collegeDetails = {};
collegeDetails.CollegeName = $('#TxtCollegeName').val();
collegeDetails.CollegeAddress = $('#TxtCollegeAddress').val();
$.ajax({
type: 'POST',
url: 'AddNewCollege.aspx/CreateCollegeData',
data: "{collegeDetails:" + JSON.stringify(collegeDetails) + "}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblResult').html('Inserted Successfully');
$('#TxtCollegeName').val('');
$('#TxtCollegeAddress').val('');
},
error: function () {
alert("An error occurred.");
}
});
});

Related

Ajax error calling web method

I am trying to set the date in a Bootstrap datetime picker based on drop down list selection change. I am using a web method (C#) to return "start date" given a "certificate ID".
I tried using "text" data type instead of "json" but keep getting "Cannot convert object of type System.String to type System.Collections.Generic.IDictionary"
I searched for this error type and could not find something that would resolve this issue.
$("#ddlCertificate").change(function () {
....
debugger
setStartDate($("#ddlCertificate").val());
});
function setStartDate(certItemID) {
var param = JSON.stringify(certItemID, null, 2);
$.ajax({
type: "POST",
dataType: "text",
contentType: "application/json; charset=utf-8",
url: "../services/easg.asmx/GetCertItemStartDate",
cache: false,
data: param,
}).done(function (result) {debugger
$("#tbStartDate").val(result.d);
}).fail(function (jqXHR, textStatus, errorThrown) {debugger
alert(textStatus + ' - ' + errorThrown);
});
}
Web Method:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string GetCertItemStartDate(string certID)
{
int iCertItemID = int.Parse(certID);
DateTime dtStartDate = CertItem.GetCertItemStartDate(iCertItemID);
string JSONresult;
JSONresult = JsonConvert.SerializeObject(dtStartDate);
return JSONresult;
}
The problem was the way the parameter was being passed. In ajax call, I had:
data: param,
and had to change it to:
$("#ddlCertificate").change(function () {
....
var certID = "{ 'certID': '" + $('#ddlCertificate').val() + "'}";
setStartDate(certID);
});
function setStartDate(certItemID) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "../services/easg.asmx/GetCertItemStartDate",
cache: false,
data: certItemID,
}).done(function (result) {
var startDate = JSON.parse(result.d);
setStartDate(new Date(startDate));
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown);
});
}

angularjs and webmethod return json

When I use jquery $ajax, I get the data as json
But when using angular http service, I get the response as xml.
This is my both code (angular and jquery ajax)
var _getList = function () {
var list = [];
var deferred = $q.defer();
$.ajax({
type: "POST",
url: '/Landing/manage/WebService.asmx/GetList',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data && data.d) {
list = data.d;
deferred.resolve(list);
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
deferred.reject(xmlHttpRequest);
}
});
//angular
$http({
method: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
url: '/Landing/manage/WebService.asmx/GetList',
headers: {
"Content-Type": "application/json"
}
}).success(function (data) {
console.log(data);
deferred.resolve(data);
})
.error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
And this is my web method code With json format return
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat =
System.Web.Script.Services.ResponseFormat.Json)]
public tblCampaignCollection GetList()
{
tblCampaignCollection coll = Campaign.AdminGetAll();
return coll;
}
The request you are performing is not a real POST Request, I had a similar issue, if you read the console network TAB you will see that it is a GET request.
What I do if I want to perform a POST in a service is the following:
function myService(xxxParam) {
var request = $http({
method: 'POST',
headers: {"Content-Type": 'text/plain; charset=UTF-8'},
url: serviceURL,
data: {
firstPostParam: "string",
secondPostParam: 1,
thirdPostParam: xxxParam
}
});
return ( request.then(handleSuccess, handleError) );
}
try with
$http({
method: 'POST',
url: '/Landing/manage/WebService.asmx/GetList',
headers: {
"Content-Type": 'application/json; charset=UTF-8'
},
data: {
dataType: "json"
}
})...
I hope it helps.

getting error on passing string as json object in ajax jquery

I'm trying to pass a string in code behind method using ajax jquery but getting a stupid error. If I pass integer only then it works fine but in case of string it's not working
this is what i've tried
csharp code
public static string GetQuickVD(string key)
{
return key.ToString();
}
jquery
$(document).ready(function () {
GetQuickVL();
});
function GetQuickVL() {
var Nid = new Array();
for (var key in localStorage) {
if (key.substring(0, 4) == "vhs-") {
Nid += key.replace('vhs-', '') + ",";
}
}
$.ajax({
type: "POST",
url: "QuickViewList.aspx/GetQuickVD",
data: '{key: ' +'345,' + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.response);
},
error: function (response) {
alert(response.error);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
use like this
data: {key: "345" }
You can also use like,
type: "GET",
url: "QuickViewList.aspx/GetQuickVD?key=355",
Edit
data: JSON.stringify({"key": "345"}),

File data null in File uploading using REST

And i have the following code
self.upload = function (file) {
var path = $('#fileUpload').val();
var fr= new FileReader();
var ID = JSON.stringify({
ID:23,
Name: file.name,
Type: file.type,
Size: file.size,
Path: path,
data:fr.readAsDataURL(file),
});
$.ajax({
cache: false,
url: "http://localhost:49589/api/files",
type: "POST",
dataType: "json",
data: ID,
contentType: "application/json; charset=utf-8",
processData: false,
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
},
error: function (json) {
alert("error" + JSON.stringify(json));
}
});
im performing file upload . and my controller is
[HttpPost]
public string upload(filesUpload f)
{
byte[] jj = f.data; // **getting null here**
string givenId = f.Path;
return givenId;
}
when i execute this and upload a file im getting null file data . where filesUpload is my model
what went wrong in my code . Im using Knockout.js for viwe and drundal SPA framework
is there any other way to do . kindly help me
FileReader.readAsDataURL reads the file asyncronically and return nothing. You should at first start read the file, then catch fr.onload event and from here create your json object and call ajax.
upd: The code will look like this:
self.upload = function (file) {
var path = $('#fileUpload').val();
var fr= new FileReader();
fr.onload = function (frEvent) {
var ID = JSON.stringify({
ID:23,
Name: file.name,
Type: file.type,
Size: file.size,
Path: path,
data:frEvent.target.result,
});
$.ajax({
cache: false,
url: "http://localhost:49589/api/files",
type: "POST",
dataType: "json",
data: ID,
contentType: "application/json; charset=utf-8",
processData: false,
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
},
error: function (json) {
alert("error" + JSON.stringify(json));
}
});
};
fr.readAsDataURL(file);
};

Sending multiple parameters to stored procedure with jQuery Ajax

I've got a web method that looks like:
[WebMethod]
public void InsertDrugNameAndColorToDatabase(string drugName,string drugColor)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("spInsertDrugText", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#drugName", drugName);
cmd.Parameters.AddWithValue("#drugColor", drugColor);
cmd.ExecuteNonQuery();
}
}
}
and a little JS:
<script type="text/javascript">
$(document).ready(function () {
$(".drugQuizzes").draggable({ tolerance: "fit" });
$(".drugAnswers").droppable({
drop: function (event, ui) {
var drugName = JSON.stringify({ "drugName": $(ui.draggable).find("span").text() });
var drugColor = JSON.stringify({ "drugColor": $(ui.draggable).css("background-color") });
console.log(drugColor);
console.log(drugName);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SendDrugName.asmx/InsertDrugNameToDatabase",
data: drugName,
dataType: "json",
success: function (data) {
//response(data.d);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".drugQuizzes").draggable({ tolerance: "fit" });
$(".drugAnswers").droppable({
drop: function (event, ui) {
var drugName = JSON.stringify({ "drugName": $(ui.draggable).find("span").text() });
var drugColor = JSON.stringify({ "drugColor": $(ui.draggable).css("background-color") });
console.log(drugColor);
console.log(drugName);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SendDrugName.asmx/InsertDrugNameToDatabase",
data: drugName,
dataType: "json",
success: function (data) {
//response(data.d);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
});
});
</script>
I have a version of the stored procedure ans JS where only one parameter is sent to the stored procedure, and that works.
From the console.log(drugName) and console.log(drugColor) I get
{"drugColor":"rgb(255, 69, 0)"}
{"drugName":"ORACEA"}
How can I make the data parameter of the ajax call take multiple parameters at once?
What are some names of general techniques that I need to be aware of for sending more than one parameter to a stored procedure at once using jQuery ajax?
Consider building an object literal on the client-side and passing that entire object to the service, thus you have one parameter in your service call, like this:
Client-side:
var myData = {};
myData.DrugName' = $(ui.draggable).find("span").text();
myData.DrugColor' = $(ui.draggable).css("background-color");
// Create a data transfer object (DTO) with the proper structure, which is what we will pass to the service.
var DTO = { 'theData' : myData };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SendDrugName.asmx/InsertDrugNameToDatabase",
data: JSON.stringify(DTO),
dataType: "json",
success: function (data) {
//response(data.d);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
Now on the service-side, you will need to build a class that represents the contents of the object literal created above, like this:
public class ServiceData
{
public string DrugName { get; set; }
public string DrugColor { get; set; }
}
Finally, change your web service code to accept one parameter, like this:
[WebMethod]
public void InsertDrugNameAndColorToDatabase(ServiceData theData)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("spInsertDrugText", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#drugName", theData.DrugName);
cmd.Parameters.AddWithValue("#drugColor", theData.DrugColor);
cmd.ExecuteNonQuery();
}
}
}
Note: The data passed from the jQuery call is automatically matched up with the class properties you have in your ServiceData class as long as the names match on both the client-side and server-side.
You can specify multiple data items like:
data: 'drugName='+ drugName + '&drugColor=' + drugColor;
You don't need to stringify it at all, you can pass the parameters as an object. Try this:
$(".drugAnswers").droppable({
drop: function (event, ui) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SendDrugName.asmx/InsertDrugNameToDatabase",
data: {
'drugName': $(ui.draggable).find("span").text(),
'drugColor': $(ui.draggable).css("background-color")
},
dataType: "json",
success: function (data) {
//response(data.d);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
});
The ajax() function will then stringify it for you and pass it across to your C# endpoint.

Categories