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
Related
I have two arrays of same object type that I am passing to a web service API. I look at the array just before it is passed to web service and each has an object in it. I put a breakpoint in API and the list is empty. Can't figure out what I am doing wrong.
I defined a DTO as:
public class AdminDTO
{
public string fn { get; set; }
public string mi { get; set; }
public string ln { get; set; }
public string email { get; set; }
public string userid{ get; set; }
}
in JS function I populate two arrays as such:
// this is done inside a foreach loop
var fn = userData.FirstName;
var mi = userData.Initial;
var ln = userData.LastName;
var email = userData.Email;
var userid = userData.UserID;
//push the object onto the array
admins.push({
"fn": fn,
"mi": mi,
"ln": ln,
"email": email,
"userid": userid
});
...
...
// clone admin list for later comparison
currAdmins = admins.slice(0);
At some point "admins" is changed through user interaction. Some objects are removed and some new ones are added. I use below to get two new arrays to hold the differences between "admins" and "currAdmins":
var adminsChanged = $(admins).not(currAdmins).length > 0 || $(currAdmins).not(admins).length > 0;
var adminsToAdd = [];
var adminsToRemove = [];
if (adminsChanged) {
adminsToAdd = $(admins).not(currAdmins);
adminsToRemove = $(currAdmins).not(admins);
}
...
// "newMapping" is a mapping of another DTO called "projctDTO", this is passed correctly to web service
doUpdate(newMapping, "projDTO", adminsToRemove, adminsToAdd);;
Now, I am trying to pass these two arrays to web serive via ajax call. They both have objects in them:
function doUpdate(mapping, jsonObjName, adminsToAdd, adminsToRemove) {debugger
$.ajax({
url: "../WebService/Blah.asmx/updateSomething",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{" + jsonObjName + ":" + JSON.stringify(mapping) + ", adminRemoveDTO: " + JSON.stringify(adminsToRemove) + ", adminAddDTO:" + JSON.stringify(adminsToAdd) + " }",
}).done(function (result) {debugger
...
});
Web service API:
public string UpdateSomething(ProjectDTO projDTO, List<AdminDTO> adminRemoveDTO, List<AdminDTO> adminAddDTO)
{
// projDTO has stuff in it but both lists are empty
....
}
I also tried calling ajax function and setting ajax data like this, but didn't work:
doUpdate(newMapping, "projDTO", adminsToRemove, "adminRemoveDTO", adminsToAdd, "adminAddDTO");
...
function doUpdate(mapping, jsonObjName, adminsToAdd, jsonObjNameAR, adminsToRemove, jsonObjNameAA) {debugger
$.ajax({
url: "../WebService/AIR.asmx/updateProject",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{" + jsonObjName + ":" + JSON.stringify(mapping) + ", " + jsonObjNameAR + ":" + JSON.stringify(adminsToRemove) + ", " + jsonObjNameAA + ":" + JSON.stringify(adminsToAdd) + " }",
Update
For testing purpose, instead of using the array that (supposedly) contains the differences to pass as parameters, I used the original arrays: "admins" and "currAdmins" and it worked. This tells me the problem is with the array resulting from the ".not" operation.
Also, when I examined the result of the ",not" operation I noticed not only it has the difference between two arrays but also an entry called "prevObject" that contains the initial set of objects. I hoe this helps in someone suggesting a solution.
You are correct in that the $(a).not(b) is not doing what you want here. jQuery's not does not do arrays. Here is how you could implement a function to create a new array that excludes all items from a that are also in b:
function filterNotIn(a, b, keySelector) {
const keysFromB = new Set(b.map(keySelector));
return a.filter(item => !keysFromB.has(keySelector(item)));
}
adminsToAdd = filterNotIn(admins, currAdmins, admin => admin.userid);
I have created an ajax call and am trying to send an object as an argument to the server but I am getting the following error:
Invalid web service call, missing value for parameter: 'itemTypes'
I have checked the itemTypes variable in javascript and it contains the expected values:
sessionStorage.itemTypeUid = "18"
sessionStorage.itemTypeName = "TABLE_NAME"
args = {CurId: 18, BaseTableName: "TABLE_NAME"}
javascript:
var itemTypes = {
CurId: parseInt(sessionStorage.itemTypeUid),
BaseTableName: sessionStorage.itemTypeName
};
aj("DeleteItem", itemTypes);
Ajax:
function aj(funcName, args) {
retval = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'ItemEdit.asmx/' + funcName,
data: JSON.stringify(args),
dataType: "json",
error: function (a, b, c) {
var errors = a + b + c
}
});
}
VB:
<WebMethod()>
Public Sub DeleteItem(itemTypes As Object)
Dim CurId = ""
Dim BaseTableName = ""
actions.DeleteItem(CurId, BaseTableName)
End Sub
You can update your web method like:
<WebMethod()>
Public Sub DeleteItem(CurId As Integer, BaseTableName As String)
actions.DeleteItem(CurId, BaseTableName)
End Sub
Please make sure parameter name here is exactly the same as the values passed in the ajax call. Even if the name is the same but the casing is different, then you might get errors. So, please double-check the variable names first. Also, remove
Dim CurId = ""
Dim BaseTableName = ""
from the method, so that there are no name conflicts.
I have one page in which, URL contains Querystring Value.
QSecID=164&QTempId=55&QSecName=New%20Temp%20Bt
When the page loads them and tries to get the value it works fine.
$(document).ready(function() {
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
var urlName = getUrlParameter('QSecName');
alert(urlName);
getImageData(urlName); //Pass Query String Value to Function
});
Now I am passing this value to C#, ASPX.CS page and try to fetch the data based on QSecName.
But i got error. Here is my Jquery function.
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
//data: '',
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("Success");
alert(JSON.parse(data.d));
}
});
}
My C# Page returns the DataSet in Jquery.
[WebMethod()]
public static string GetImageData(string dataSecName)
//public static string GetRole()
{
clsSection objSectNew = new clsSection();
DataSet DS = new DataSet();
DS = objSectNew.GetImageDataByJQ(dataSecName);
return JsonConvert.SerializeObject(DS);
}
Edit Code 1
Here is my SQL Statement Which is get executed when i run the page and
DS = objSectNew.GetImageDataByJQ(dataSecName);
this method pass the query string value in to execute the Stored Procedure.
select mhp.ImageName,mhp.HotSpotID,imgdetail.XCordinate,imgdetail.YCordinate
from tbl_SOAPDetailsInfo e inner join M_ImageHotSpot mhp on e.ImgHotSpotName=mhp.ImgHotSpotNameByUser
inner join M_ImageHotSpotDetail imgdetail on mhp.HotSpotID=imgdetail.HotspotIDFK where e.SOAP_D_Name='New Temp Bt'
I want to use my XCordinate, YCordinate and ImageName to display image using jquery. but Inside the alert BOX
**[object] [object]**
error display. How can i get and assign this value X AND Y value and display in DIV.
Edit Code 2
ImageName XCordinate YCordinate
$parent in angularjs.png 1146 590
$parent in angularjs.png 1216 588
$parent in angularjs.png 1188 626
$parent in angularjs.png 1162 582
$parent in angularjs.png 1193 586
The Database Value. JSON FORMAT DATA
{"d":"{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"}
So as per your question [object] [object] is not an error. It means you cannot fetch it in a correct manner.
Though I am not sure what kind of data you are sending from your back-end code in data But you could try following way,
var data = "{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
So now if you replace your code with above sample your code should look like below:
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
});
}
Note : Try to debug in browser console you would understand object notation more details.
See the screen shot how would you do that
Hope this would help
this is my ajax call function
$.ajax({
url: "webservices/mywebserveice.vb",
data: "{'myactivity':'" + myactivity + "','myproddate':'" + mynewprddatee + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
success: function (data) {
var obj = jQuery.parseJSON(data.d);
//obj[0]["ColumnName"]
var returnlist = new Array();
my vb. code returns some data and pass I to ajax call using
Return New JavaScriptSerializer().Serialize(rows) .It stops at var obj in ajax call for some data but it is not stopping when i pass some other data in vb file. even if i have identical dataset result.
here is a part of vb code
'Convert Dataset to DataReader
Dim dr As DataTableReader = ds.Tables(0).CreateDataReader()
If dr.HasRows Then
Do While dr.Read()
row = New Dictionary(Of String, Object)
For c As Integer = 0 To dr.FieldCount - 1 '//fieldcount gives the column count.
row.Add(dr.GetName(c), dr.GetValue(c)) '//getname->gets the column name; getvalue->gets the col value.
Next
rows.Add(row)
Loop
End If
Return New JavaScriptSerializer().Serialize(rows)
I also tried asycn = false/ture , same issue ..
Any help appreciate
This is a simplified code. I have a webservice (.asmx) as following:
I store some values in Test class and then store the class in an arraylist.
I do this two times in two different arraylists.
and then store these two array lists in a third arraylist.
and then pass this arraylist as output of webmethod.
private class Test
{
public string Id;
public string Name;
}
[webmethod]
public ArrayList RuleReport(long RuleId)
{
Test t = new Test();
t.Id = "1";
t.Name = "a";
ArrayList ar = new ArrayList();
ArrayList ar2 = new ArrayList();
ArrayList ar3 = new ArrayList();
ar.Add(t);
t = new Test();
t.Id = "2";
t.Name = "b";
ar2.Add(t);
ar3.Add(ar);
ar3.Add(ar2);
return ar3;
}
and in js file I want to parse he json result to read each Id and Name values of two arraylists.
id=1,name=a
id=2,name=b
this is my jquery code:
$.ajax(
{ url: " Ajaxes/Rules.asmx/RuleReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
data: "{'RuleId':'79'}",
async: false,
success: function(data) {
$.each(data.d, function(index, obj) {
alert(obj.d[0].Id);// something like this. How to do it???
})
}, error: function() { }
});
this is the json response in fire bug:
{"d":[[{"Id":"1","Name":"a"}],[{"Id":"2","Name":"b"}]]}
how to get every Id and Name values???
With your current setup inside $.each loop you are getting
[{"Id":"1","Name":"a"}]
as obj. As you can see it's a array of object with only one object as it's content. You can access that object with obj[0] and then their properties can be accessed with obj[0].Id and obj[0].Name
You can do this with the following code
$.each(data.d,function(index,obj){
var id = obj[0].Id;
var name = obj[0].Name;
// do what ever you want with them
})
Working fiddle