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);
});
}
Related
I have a string function ASP.Net Webform. I want to call this function using AJAX.
That function returns a string value from database with a month index
protected string BringDatas(int month)
{
Counts counts_ = new Counts();
return counts_.GetMonths(month);
}
var dataValue = { "month": 1 };
$.ajax({
type: "POST",
url: "Homepage.aspx/BringDatas",
data: dataValue,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
complete: function (jqXHR, status) {
alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
}
});
Give it a try:
Code Behind:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string BringDatas(int month)
{
Counts counts_ = new Counts();
return counts_.GetMonths(month);
}
ajax call
$.ajax({
type: 'GET',
url: 'Homepage.aspx/BringDatas',
data: '{"month": 1}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: false,
success: function (response) {
alert("Response: " + response.d);
},
error: function (response) {
}
});
This is javascript side
<script type="text/javascript">
$(document).ready(
function () {
$("#Gonder").click(
function () {
$.ajax
({
type: "POST",
url: "Homepage.aspx/OrnekPost",
data: "{'parametre':'1234'}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (output) {
alert("Response: "+ output);
}, error: function () {
alert("hata var");
}
});
});
})
</script>
Codebehind.cs code
[ScriptMethod]
[WebMethod(EnableSession = true)]
public static string OrnekPost(string parametre)
{
return parametre + " değeriyle post işlemi gerçekleştirildi.";
}
I'm trying to send a json list populated with the id's from the 'data-seq' attribute only when the 'value' == true.
I have tried out a lot solution but it keeps getting me error messages, the most common are "there is no parameterless constructor for the type string" when using string[] or "string is not supported for deserialization of an array" when using string as code-behind parameter in the WebMethod.
function sentData() {
var json = [];
$('.btn[value="true"]').each(function () {
var obj = {
id: $(this).attr("data-seq")
};
json.push(obj);
});
json = JSON.stringify({ jsonList: json });
console.log(json); // {"jsonList":[{"id":"38468"},{"id":"42443"},{"id":"42444"}]} (the right id's are getting stored)
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/getList",
dataType: "json",
data: json,
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function(json){
//do something with the result
}
});
return false;
}
// Code-Behind
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
// string: string is not supported for deserialization of an array
// string[]: there is no parameterless constructor for the type string
}
You are just sending IDs so send them as comma-separated string like this:
function sentData() {
var json = [];
$('.btn[value="true"]').each(function () {
var id = $(this).attr("data-seq")
json.push(id);
});
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/getList",
dataType: "json",
data: '{jsonList: "' + json + '" }',
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function(json){
//do something with the result
}
});
return false;
}
And Code-Behind:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
List<string> ListOfIDs = jsonList.Split(',').ToList();
}
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.");
}
});
});
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"}),
I am trying to achieve a simplest task through ajax using web method . My web method as follow
[WebMethod]
public static string GetDate()
{
return string.Format("says {0}", DateTime.Now.ToString("r"));
}
and ajax code as follow
$(document).ready(function() {
$("#Result").click(function() {
alert('Result Clicked');
$.ajax(
{
type: "POST",
url: "test1.aspx/GetDate",
data : "{}",
contentType: "application/json",
dataType: "json text",
success: function(rsp) {
alert('success');
alert(rsp);
alert(rsp.d);
$('#Result').append(rsp.d);
},
error: function(rsp) {
alert(rsp.status + " " + rsp.statusText + "</br>" + rsp.responseText);
console.log(rsp);
console.log(rsp.responseText);
}
});
});
});
but status says OK and 200 status code, but instead of simple string in rsp.d its shows complete HTML of that page self.
You Can Try this Code May be it is Help Full.
$("#Result").click(function () {
alert('Result Clicked');
$.ajax(
{
type: "POST",
url: "Default.aspx/GetDate",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (rsp) {
alert('success');
alert(rsp);
alert(rsp.d);
$('#Result').append(rsp.d);
},
error: function (rsp) {
alert(rsp.status + " " + rsp.statusText + "</br>" + rsp.responseText);
}
});
});