I currently have a list of dates in my code-behind, I'd like to pass the list to a variable in javascript without the use of hiddenfield
For instance,
Aspx.cs:
List < DateTime > blockedDate = new List < DateTime > ();
foreach(DataRow blockedRow in phBLL.getAllPH(DateTime.Now.Year).Tables[0].Rows)
{
blockedDate.Add(Convert.ToDateTime(blockedRow["date1"]));
}
Aspx:
$(document).ready(function () {
var arrayOfDates = ""
});
What I've tried
Aspx.cs:
public static List < DateTime > blockedDate = new List < DateTime > ();
[WebMethod]
public static List < DateTime > blockDates()
{
foreach(DataRow blockedRow in phBLL.getAllPH(DateTime.Now.Year).Tables[0].Rows) {
blockedDate.Add(Convert.ToDateTime(blockedRow["date1"]));
}
return blockedDate;
}
Javascript:
$.ajax({
type: "POST",
url: "CreateClass.aspx/blockDates",
data: null,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function(result) {
for (var i = 0; i < result.d.length; i++) {
var dates = [new Date(parseInt(result.d[i].substr(6)))];
console.log(dates);
}
}
});
I am trying to get the result and place into an Array. So it'd end up something like this
an array of dates
var array = ["2016/11/14", "2016/11/15", "2016/11/16"];
As per comments, Create a [WebMethod] which contain your code behind logic and call it using ajax.
Now, you will get data on ajax success, and just push your data to array arrayOfDates using JavaScript Array push() Method
Hope this helps!
Related
I am building a WCF service in C# in which I would like to be able to return multiple values from some of my functions. The code below appears to do this:
[WebMethod]
public void ReturnMultipleValues(int startingValue)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var jsonData = new { FirstValue = startingValue, SecondValue = startingValue * 2 };
Context.Response.Write(ser.Serialize(jsonData));
}
I am trying to access this function through an ajax call in JavaScript code:
function runTestService() {
$.ajax({
type: "POST",
url: "http://localhost:12345/WebServices/MyService.asmx/ReturnMultipleValues",
contentType: "application/json;charset=utf-8",
data: "{ 'startingValue' : 6 }",
dataType: "json",
done: function(data) {
var firstValue = data.FirstValue;
var secondValue = data.SecondValue;
alert("First: " + firstValue + ", Second: " + secondValue);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
}
When I execute the above JavaScript code, the function in the .done portion never executes. When I check Fiddler, however, I see that the function in my service did execute properly and returned the correct values in the JSON.
Is there another way I should code either the service or the ajax call to it?
You are not supposed to write to Context.Response by yourself. Just return an object from method and let the framework do it for you
[WebMethod]
public object ReturnMultipleValues(int startingValue)
{
var jsonData = new { FirstValue = startingValue, SecondValue = startingValue * 2 };
return jsonData;
}
And you have to consider the fact web service wraps json repsonse in object with d property
{
"d": {
"FirstValue": 6,
"SecondValue": 12
}
}
So update js as well
done(function (data) {
data = data.d;
var firstValue = data.FirstValue;
var secondValue = data.SecondValue;
alert("First: " + firstValue + ", Second: " + secondValue);
});
I'm a beginner and I want to use ajax to load some data from database to dropdownlist when another dropdownlist selected index in changed
but I'm getting nothing but 500 error
My jquery ajax code
function ddlGroups() {
var s = $("#Content_ddlGroups").find("option:selected").prop("value");
$.ajax({
method: "GET",
contentType: "application/json; charset=utf-8",
//url is the path of our web method (Page name/function name)
url: "../panels/admin/AddProject.aspx/getSubgroups",
data: { Id: s },
dataType: "json",
//called on jquery ajax call success
success: function (result) {
$('#Content_SubGroups').empty();
$.each(result.d, function (key, value) {
$("#Content_ddlGroups").append($("<option></option>").val(value.GroupID).html(value.Title));
});
},
//called on jquery ajax call failure
error: function ajaxError(result) {
alert(result.status + ' : ' + result.statusText);
}
});
};
and my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<Group> getSubgroups(string Id)
{
DataTable dt = new DataTable();
List<Group> objDept = new List<Group>();
GroupsRepository jg = new GroupsRepository();
//Page page = (Page)HttpContext.Current.Handler;
//DropDownList DDLGroups = (DropDownList)page.FindControl("DDLGroups");
dt = jg.LoadSubGroup(Id.ToInt());
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objDept.Add(new Group
{
GroupID = Convert.ToInt32(dt.Rows[i][0]),
Title = dt.Rows[i][1].ToString(),
});
}
}
return objDept;
}
What is the problem??
The jQuery is not the problem here. The 500 error is thrown by the server, so you should review the log of your c# code to find out the details about it and be able to narrow the causes.
In your AJAX Call actually 500 error caused beacuse you have passed
Id:s instead of Id having some digits. Ex. Id : 5.
I see your code if you passed string as a id so in your server side method
you are trying to convert that string to int.That actually causes the 500 error.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<Group> getSubgroups(string Id)
{
DataTable dt = new DataTable();
List<Group> objDept = new List<Group>();
GroupsRepository jg = new GroupsRepository();
//Page page = (Page)HttpContext.Current.Handler;
//DropDownList DDLGroups = (DropDownList)page.FindControl("DDLGroups");
dt = jg.LoadSubGroup(Id.ToInt()); // Here You have convert string to Int that's why you got 500 Error.
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objDept.Add(new Group
{
GroupID = Convert.ToInt32(dt.Rows[i][0]),
Title = dt.Rows[i][1].ToString(),
});
}
}
return objDept;
}
I'm using asp.net web forms and trying to call a web service method from a java script function using AJAX which returns a JSON array with a car number and a car number ID pairs
the web methods resides in the same code behind file of the java script function page
I checked the json variable more than one time using the debugger and made sure it holds a valid JSON array
however when I checked the cars object in the FillLimoCars java script function I found the response text to be an empty array
I'm not sure why this is happening I hope that anyone of you would be able to help
Java Script
function testButton(carModelID) {
$.ajax({
type: "POST",
url: baseURL + "WebPages/NewPages/ListCarRental.aspx/FillLimoCars",
data: "{CarModelID:'" + carModelID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: FillLimoCar
});
}
function FillLimoCar(cars)
{
var rdd_LimoCars = $find("<%=rdd_LimoCarNumber.ClientID %>");
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
for(var i = 0; i < cars.length; i++)
{
;
}
}
C#
[WebMethod]
public static string FillLimoCars(int CarModelID)
{
try
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<LimoFleet> limos = carsBLL.GetCarModelLimoFleet(CarModelID);
List<object> objLimosList = new List<object>();
foreach(var limo in limos)
{
var limoObj = new
{
CarID = limo.CarID,
CarNumber = limo.CarNumber
};
objLimosList.Add(limoObj);
}
var json = serializer.Serialize(objLimosList);
return json;
//Context.Response.Write(objLimos.ToJson());
}
catch (Exception ex)
{
Tracer.Singleton.Log(ex);
return null;
}
}
You have to use success attribute. Inside success, you have to de serialize JSON object.
$.ajax({
type: "POST",
url: baseURL + "WebPages/NewPages/ListCarRental.aspx/FillLimoCars",
data: "{CarModelID:'" + carModelID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
"success": function (json) {
if (json.d != null) {
FillLimoCars(json.d);
}
});
I know now how to use the page method in JavaScript and ASP.Net (VB.Net) but it only limits me with single insertion. My problem is when I will insert to database in bulk with column items in gridview. It's not working and unfortunately, it doesn't say any error. This is I have so far:
Server-side code (VB)
<WebMethod()> _
<ScriptMethod()> _
Public Shared Sub SavetoDB(ByVal ans As Answers)
Dim constr As String = ConfigurationManager.ConnectionStrings("CCQTConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("INSERT INTO tblApplicantAns (Appnr, QID, answer) VALUES(#Appnr, #QID, #ans)")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Appnr", ans.appnr)
cmd.Parameters.AddWithValue("#QID", ans.qid)
cmd.Parameters.AddWithValue("#ans", ans.ans)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
Public Class Answers
Public Property qid() As String
Get
Return _qid
End Get
Set(ByVal value As String)
_qid = value
End Set
End Property
Private _qid As String
Public Property ans() As String
Get
Return _ans
End Get
Set(ByVal value As String)
_ans = value
End Set
End Property
Private _ans As String
Public Property appnr() As String
Get
Return _appnr
End Get
Set(ByVal value As String)
_appnr = value
End Set
End Property
Private _appnr As String
JavaScript (AJAX)
$(function () {
var gvDrv = document.getElementById("<%= grdQ.ClientID %>");
for (i=1; i<gvDrv.rows.length; i++)
{
var cell = gvDrv.rows[i].cells;
var q = cell[0].innerHTML;
var a = cell[1].innerHTML;
$("[id*=Button1]").bind("click", function () {
var ans = {};
ans.appnr = $("[id*=TextBox1]").val();
ans.qid = $(" + q + ").val();
ans.ans = $(" + a + ").val();
$.ajax({
type: "POST",
url: "English.aspx/SavetoDB",
data: '{ans: ' + JSON.stringify(ans) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Time is up! Exam will proceed to next module.");
window.location = "Conf_English.aspx";
}
});
return false;
});
});
}
Since you have a single save button for the whole grid, then you have your client-script logic backwards. You will want to loop through each row of the grid in the click event handler for the button, instead of the other way around; like this:
$(document).ready(function() {
$("[id*=Button1]").bind("click", function() {
var gvDrv = document.getElementById("<%= grdQ.ClientID %>");
for (i = 1; i < gvDrv.rows.length; i++) {
var cell = gvDrv.rows[i].cells;
var q = cell[0].innerHTML;
var a = cell[1].innerHTML;
var ans = {};
ans.appnr = $("[id*=TextBox1]").val();
ans.qid = $(" + q + ").val();
ans.ans = $(" + a + ").val();
$.ajax({
type: "POST",
url: "English.aspx/SavetoDB",
data: '{ans: ' + JSON.stringify(ans) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Time is up! Exam will proceed to next module.");
window.location = "Conf_English.aspx";
}
});
}
return false;
});
});
Now instead of calling the page method for each row in the grid you need to pass an array of values to the server-side ASP.NET AJAX Page Method instead of a single value. To leverage the Answers class you already have defined, we can build up a JavaScript array of objects that have property values that match the name of your properties in your class (i.e. qid, ans, etc.); like this:
$(document).ready(function() {
$("[id*=Button1]").bind("click", function() {
var gvDrv = document.getElementById("<%= grdQ.ClientID %>");
// Create array to hold x number of Answers instances
var answers = new Array();
// Loop through rows of grid
for (i = 1; i < gvDrv.rows.length; i++) {
var cell = gvDrv.rows[i].cells;
var q = cell[0].innerHTML;
var a = cell[1].innerHTML;
// Build one answer object per row
var ans = {};
ans.appnr = $("[id*=TextBox1]").val();
ans.qid = $(" + q + ").val();
ans.ans = $(" + a + ").val();
// Add single answer to array of answer objects
answers.push(ans);
}
// Make one call to ASP.NET AJAX Page Method passing in array of answer values
$.ajax({
type: "POST",
url: "English.aspx/SavetoDB",
data: '{ans: ' + JSON.stringify(answers) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Time is up! Exam will proceed to next module.");
window.location = "Conf_English.aspx";
}
});
return false;
});
});
Finally, on the server-side in your ASP.NET AJAX Page Method, you will need to handle a list of Answers objects instead of a just a single Answers object, like this:
<WebMethod()> _
<ScriptMethod()> _
Public Shared Sub SavetoDB(ByVal ans As List(Of Answers))
Dim constr As String = ConfigurationManager.ConnectionStrings("CCQTConnectionString").ConnectionString
' Loop through each Answers object here
For Each answer As Answers In ans
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("INSERT INTO tblApplicantAns (Appnr, QID, answer) VALUES(#Appnr, #QID, #ans)")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Appnr", answer.appnr)
cmd.Parameters.AddWithValue("#QID", answer.qid)
cmd.Parameters.AddWithValue("#ans", answer.ans)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Next
End Sub
I have this function in jquery which has the result array and how can I get this result array to C# code. Can anyone help me regarding this.
function generateData() {
var result = $('#accordion').sortable('toArray');
}
You could do this asynchronously through a web method call from script, such that you define a web method appropriately, then call and handle the data and potential return value, as desired. For example:
Defining a web method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string HandleData(object[] data)
{
//handle data
return string.Empty;
}
Defining a reusable jQuery script method to handle web method calls:
function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
$.ajax({
type: "POST",
url: page + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
});
}
And, of course, the call itself:
ExecutePageMethod("Default.aspx", "HandleData",
["data", result], successCallback, failureCallback);
Naturally we now need to make sure our callback methods exist:
function successCallback(result) {
var parsedResult = jQuery.parseJSON(result.d);
}
function failureCallback(result) {
}
Use a hiddenfield to store the result..
<asp:HiddenField id="hfResult" runat="server" />
JQuery
$('hfResult').val(result);
C#
String result = hfResult.Value;
Note that a hiddenField only holds a string, so you might need to use some kind of seperator to seperate your array objects..