Ajax call to Asp.net Web Method using Jquery - javascript

I am using a jquery method, to send information (namely only member identification #) from client side to the server side.
The server side has the traditional Web Method implemented so as to capture data sent and execute SQL queries based on it.
Web-service-method-using-jQuery
However until now I have been returning a single string from the server side back to the client side after the SQL query.
Wondering what would be the best way to return a complicated series of strings... member Identification number, start date, end date, type of member... depending on the type of the member, there can be multiple start dates and end dates.
Should I be looking into XML ?

What about returning even a datatable
$.ajax({
type: "POST",
url: "YourPage.aspx/doSomething",
data: "{'id':'1'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var returnedstring = data.d;
var jsondata = $.parseJSON(data.d);//if you want your data in json
}
});
aspx:
[WebMethod]
public static string doSomething(int id)
{
....
DataTable dt = new DataTable();
dt = anothermethodReturningdt(id)
return JsonConvert.SerializeObject(dt);
}
You can use json.net for serializing .Net objects
Edit
you can also do this
[WebMethod]
public static string doSomething(int id)
{
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
return JsonConvert.SerializeObject(product);
}
The point is you can serialize any type of object, arrays, collections etc and then pass it back to the calling script.

Related

Trying to make an Ajax call to a web form method and getting an internal server error. I have tried almost all solutions to similar questions

The function getClientData() gets called from one of the anchor tags in a grid's column. The anchor tag has a couple of Data-Tags which are passed to the code behind method. I have to perform some DB operation through these parameters but before that I wanted to make sure if this prototype would work.
This is how the anchor tag looks:
Show
This is my Javascript method:
function getClientData() {
//var dataValue = { "keyData": this.event.target.getAttribute("data-kt"), "valueData": this.event.target.getAttribute("data-kv")};
$.ajax({
type: "GET",
url: "Clients.aspx/GetClientData",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ keyData: this.event.target.getAttribute("data-kt"), valueData: this.event.target.getAttribute("data-kv")}),
dataType: 'json',
error: function (error) {
alert(error.statusText);
},
success: function (result) {
alert("Success: " + result );
}
});
}
I put a break point here and it never gets triggered. This is my web method in the code behind file:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string keyData, string valueData)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}
This is the URL that gets created for the POST request "http://localhost:60825/Clients.aspx/GetClientData?{%22keyData%22:%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22,%22valueData%22:%221p7q9%22}". Please let me know if I am doing something wrong.
I am not sure how you configured routing but based on your API method (code behind) your data should be formatted in following manner:
Method 1:
http://localhost:60825/Clients.aspx/GetClientData?keyData=Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy&valueData=1p7q9
As you can see, instead passing stringified JSON object I am sending data in format of query string where keyData and valueData has corresponding values.
Method 2:
If you prefer to send stringified JSON you can modify your Payload in URL like this:
http://localhost:60825/Clients.aspx/GetClientData?data=%7BkeyData%22%3A%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22%2C%22valueData%22%3A%221p7q9%22%7D
Here I am sending stringified JSON as data parameter in query string. For that purpose your code behing method needs to be like this:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string data)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}

Passing XMLDocument to Stored Procedure

My current setup is as follows:
Client Javascript JSON stringified object is passed to a server function as so
Client:
var requestObject = JSON.stringify(clientObject);
$.ajax({
url: 'ServerClass.aspx/ServerFunction',
data: requestObject,
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
context: document.body,
type: 'POST',
success: saveSuccessfulFunction
});
Server:
[WebMethod(EnableSession = true)]
public static int SaveAllReportOptions(string requestObject)
{
XmlDocument xdoc = JsonConvert.DeserializeXmlNode("{\"root\":" + clientObject + "}", "roots");
DBClass.Save(xdoc);
}
public int Save(XmlDocument clientObject)
{
SqlCommand dCmd = new SqlCommand("MyStoredProcedure", conn);
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.AddWithValue("#objectXML", SqlDbType.Xml).Value = clientObject.InnerXml;
SqlParameter returnValue = dCmd.Parameters.Add("#ret", SqlDbType.Int);
returnValue.Direction = ParameterDirection.ReturnValue;
conn.Open();
dCmd.ExecuteNonQuery();
conn.Close();
int i = Convert.ToInt32(dCmd.Parameters["#ret"].Value);
return i;
}
The stored procedure successfully extracts the different nodes/attributes from the XMLDocument passed in and goes on to perform the relevant update/insert commands.
SELECT tab.col.value('att1[1]','NCHAR(10)') as attribute1,
tab.col.value('att2[1]','INT') as attribute2...
FROM #objectXML.nodes('/roots/root') AS tab(col)
My issue isn't with the above code but with certain do's and don'ts observed from various online/in house software coding standards.
Source 1
X DO NOT use XmlNode or XmlDocument to represent XML data. Favor using instances of IXPathNavigable, XmlReader,XmlWriter, or subtypes of XNode instead. XmlNode and XmlDocument are not designed for exposing in public APIs.
Source 2
✓ DO use XmlReader, IXPathNavigable, or subtypes of XNode as input or output of members that accept or return XML.
Use these abstractions instead of XmlDocument, XmlNode, or XPathDocument, because this decouples the methods from specific implementations of an in-memory XML document and allows them to work with virtual XML data sources that expose XNode, XmlReader, or XPathNavigator.
Source 3
X DO NOT subclass XmlDocument if you want to create a type representing an XML view of an underlying object model or data source.
Basically, I would like to know if it is safe and reliable enough to use XMLDocument for the purpose detailed above. And if not, if there are any alternatives which would be better suited for my scenario.
I used this approach -
For e.g. You have customer object with multiple orders ( child classes)
1. At client side - after assigning values in both the classes
customerObject = JSON.stringify(cls_m_Customer, function(k, v){ return v === "" ? "" : v });
2. At server side -
JavaScriptSerializer jss = new JavaScriptSerializer();
cls_m_Customer objCustomer = new cls_m_Customer();
objCustomer = jss.Deserialize<cls_m_Customer>(customerData);
3. At Business Class - create two dictionaries for customer and orders classes and add these tables to dataset and then convert ds into xml like -
Dictionary<string, cls_m_Customer> dic_Customer = new Dictionary<string, cls_m_Customer>();
dic_Customer.Add("1", this);
DataSet ds = new DataSet();
DataTable dtCustomer = DictionaryToDataTable.ConvertTo<cls_m_Customer>(dic_Customer, "Customer");
DataTable dtOrders = DictionaryToDataTable.ConvertTo<cls_m_Order>(this._Order, "Orders");
ds.Tables.Add(dtCustomer);
ds.Tables.Add(dtOrders);
DataRelation drQ = new DataRelation("Customer Related Orders", dtCustomer.Columns["_CustomerID"], dtOrders.Columns["_CustomerID"]);
drQ.Nested = true;
ds.Relations.Add(drQ);
customerXml = ds.GetXml();

How to print array list data using ajax?

I am new to AJAX and JSON. I have an ArrayList which contains another ArrayList and I converted the whole array in to JSON object:
#Produces(MediaType.APPLICATION_JSON)
public String getRecords(#QueryParam("mobile_no") String mobilenumber) {
UserActivityDelegate delegate = new UserActivityDelegate();
List<AssessmentDTO> list = delegate.getLastFiveAssessment(mobilenumber
.trim());
if (list.isEmpty())
return "Sorry....You have not attended any assessment";
else {
System.out.println(list);
return (new Gson()).toJson(list);
}
Now I want to know how can I retrieve or iterate the response object in JSP using ajax??
In Ajax response you receive a response string you can convert that either to javascript list or json and iterate over them.
Like below:
jQuery.ajax({
type: 'POST',
url: your_url_string,
data: 1=1 //params,
async: false,
success: function(response,textStatus){
json= JSON.parse(response);
},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
then json object is what you need to take care of.

MVC 3 jquery ajax post 2 objects

I have a controller action that takes two objects as arguments. I can't get it to work at all they always come back as null. My latest try looks like below. I have tried many other variations. In this case the FormInfo class is a class with 2 properties that are types for Form1 and Form2. I have also tried having the controller take in the two classes as arguments and the data part looked like { form1: form1Data, form2: form2Data } that was not working as well. I also tried using JSON.stringify to form the data with no luck.
Looking in the network monitor I see the data going back to the server it's just the engine that MVC uses to decode the query string to the objects can't handle what I'm passing back.
Thanks in advance for any information!
ClientSide
var formData = $("#form1").serialize();
var formData2 = $("#form2").serialize();
var formInfo = new Object();
formInfo.FormData = formData;
formInfo.FormData2 = formData2;
$.ajax({
url: 'Controller/Action',
type: 'POST',
data: formInfo,
success: function (data) {
//do stuff
}
});
ServerSide
public ActionResult SaveForms(FormInfo formInfo)
{
//Do Stuff here
}
You could use the a JSON request in conjunction with the .serializeArray() jQuery method. Let's suppose that you have the following model:
public class FormInfo
{
public Form1Data Form1Data { get; set; }
public Form2Data Form2Data { get; set; }
}
where Form1Data and Form2Data are some completely arbitrary complex classes. Now on the client we suppose that you have 2 distinct forms (#form1 and #form2 whose input element names match your complex structures in terms of default model binder wire format). Sending an AJAX request and packing the 2 forms together becomes trivial:
var form1Data = {};
$.each($('#form1').serializeArray(), function () {
form1Data[this.name] = this.value;
});
var form2Data = {};
$.each($('#form2').serializeArray(), function () {
form2Data[this.name] = this.value;
});
$.ajax({
url: '#Url.Action("someaction", "somecontroller")',
type: 'post',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
form1Data: form1Data,
form2Data: form2Data
}),
success: function (result) {
// TODO: do something with the result
}
});
And of course the controller action you are POSTing to looks like this:
[HttpPost]
public ActionResult SomeAction(FormInfo formInfo)
{
...
}
I am doing something like this but i have a object and other Formdata to pass my Controller
var discrepancy = self.newCptyReply();
if ($('#UploadFile')[0]) {
var upload = new FormData(),
file = $('#UploadFile')[0].files[0];
upload.append('id', self.globalMessageId());
upload.append('discrepancy', ko.toJSON(discrepancy));
upload.append('doc', file);
}
datacontext.saveCptyToReply(self, upload);
And in controller signature
public ActionResult SaveCptyToReply(Guid id, Trade discrepancy, HttpPostedFileBase doc)
But when it reaches Controller id , doc are ok but discrepancy is null... It has data when funciton is called..
What to do...

Returning json in asp.net webservice

In my application,we use the prototype1.4.2 in the page.
And we need the tree view which support lazy load(make a ajax request and add the data from the server to the node),then I found the
TafelTree
It is built based on the prototype.
And there is a function:
onopenpopulate:
It will load data from the server according the "openlink" provided by user.
Called after a branch is opened. When it's open, it launch an Ajax
request at the page openlink and send the Ajax response to the user
function. It must return a JSON string representing an array of one or
more TafelTreeBranch. Override setOnOpenPopulate() of TafelTree
But it need the server return pure json data format.
And I have created a webservice this way:
[WebService(Namespace = "http://microsoft.com/webservices/";
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UtilService: WebService {
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string loadData(id) {
//some logic according the id
return "{id:0,name:'xx'}";
}
}
However when I invoke this service use:
http://xxx/UtilService/loadData?id=0
I always get the xml format.
Through google,it seems that I have to set the "content-type" when make the ajax request.
However,in my case,the ajax is sent by the "TafelTree",I can not add extra parameters.
Any idea? or use another prototype based tree?
you can use jquery to do an Ajax call.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "webServiceUrl/MethodName",
data: "{Id: '" + id + "'}",
dataType: "json",
success: loadSucceeded,
error: loadFailed,
async: true
});
function loadSucceeded(result, status)
{
var data = result.d;
}
function loadFailed(result, status)
{
}
Note that it is not necessarily to return a string, you can return a list of object.
[WebService(Namespace = "http://microsoft.com/webservices/";
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UtilService: WebService
{
[WebMethod]
public List<string> loadData(id) {
//some logic according the id
return new List<string>(){"data"};
}
}

Categories

Resources