How to pass an array to asmx web service via JSON? - asp.net

I want to pass array value to my web service file. But it throws the following error
setDeleteFiles
Test
The test form is only available for methods with primitive types as parameters.
Here is my jquery code
$('#btnDeleteFiles').click(function () {
var filesPaths = [];
i = 0;
$("input:checkbox[name=filed-checkedbox]:checked").each(function () {
filesPaths[i] = $(this).val();
i++;
});
//alert("filesPaths = " + filesPaths)
var location = $('#ddlLocation option:selected').text();
alert("Location = "+location)
$.ajax({
method: 'post',
url: "GetAllFolderDetails.asmx/setDeleteFiles",
data: {
location: location,
fileNames: filesPaths
},
dataType: "json",
success: function (data) {
window.location.reload(true);
//alert("Success");
},
error: function (result) {
alert("Error");
}
});
});
GetAllFolderDetails.asmx code
[WebMethod]
public void setDeleteFiles(string location, string[] fileNames)
{
var locationID = 0;
var domain = "domain";
var username = "xxx"; //username
var Password = "***"; //password
Debug.WriteLine("Location = "+location);
Debug.WriteLine("fileNames = " + fileNames);
using (new ImpersonateUser(username , domain, Password))
{
Debug.WriteLine("Files names = "+ fileNames);
foreach (string file in fileNames)
{
FileInfo files = new FileInfo(file);
files.Delete();
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize("Files are successfully Deleted"));
}
}
Note
If I pass a string as a parameter without an array, it is working fine

Use the following
data: JSON.stringify({ location: location, fileNames: filesPaths }),
contentType: "application/json; charset=utf-8",
dataType: "json",
and change the input parameter datatype as List<string> instead of string[]

Just remove
dataType: "json",
from your ajax call.
and also check in your asmx file that it is decorated with
[System.Web.Script.Services.ScriptService]
try this.

Related

asp.net web forms [WebMethod]

I have a problem with my [WebMethod] when I return Json data List<Contract> from DB using Entity Framework
function populateData(pageIndex) {
// populate data from database
$.ajax({
url: "/Pages/App/Docs.aspx/PopulateDataByJquery",
data: "{pageNo: " + pageIndex + ", noOfRecord: 7}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: onError
});
}
function OnSuccess(data) {
alert('good');
}
function onError() {
alert('Failed!');
$('#LoadingPanel').css('display', 'none');
}
This my WeMethod.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Contract> PopulateDataByJquery(int pageNo, int noOfRecord)
{
System.Threading.Thread.Sleep(2000);
Entities4 db = new Entities4();
List<Contract> data = new List<Contract>();
int skip = (pageNo - 1) * noOfRecord;
data = db.Contracts.Include("PhysicalPerson").Include("Product").OrderBy(a => a.Id).Skip(skip).Take(noOfRecord).ToList();
return data;
}
I every time getting ajax error, help me please! I don't know how it fix.
You have to make some changes to your ajax call and WebMethod
function populateData(pageIndex) {
// populate data from database
$.ajax({
url: "Docs.aspx/PopulateDataByJquery",
data: "{pageNo: pageIndex, noOfRecord: 7}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: onError
});
}
function OnSuccess(data) {
alert('good');
}
function onError() {
alert('Failed!');
$('#LoadingPanel').css('display', 'none');
}
Change your WebMethod
[WebMethod]
public static string PopulateDataByJquery(int pageNo, int noOfRecord)
{
System.Threading.Thread.Sleep(2000);
Entities4 db = new Entities4();
List<Contract> data = new List<Contract>();
int skip = (pageNo - 1) * noOfRecord;
data = db.Contracts.Include("PhysicalPerson").Include("Product").OrderBy(a => a.Id).Skip(skip).Take(noOfRecord).ToList();
JavaScriptSerializer TheSerializer = new JavaScriptSerializer()
var TheJson = TheSerializer.Serialize(data);
// for this you need to add using System.Web.Script.Serialization;
return TheJson;
}
For more read this

calling webmethod using jquery

I am having two asp textboxes, TextBoxPicPostCode and TextBoxPicAddress.
The goal of this task is that when i enter a post code in TextBoxPicPostCode and the focus gets lost from this TextBox it should automatically populate TextBoxPicAddress using the method in code behind.
The method getadd() in .cs code works fine and uses google api but i am not getting an idea how to use jquery ajax with it.
Code-Behind
public void getadd()
{
string address = "";
//_Address.InnerText = _PostCode.Text;
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://maps.google.com/maps/api/geocode/xml?address=" + TextBoxPicPostCode.Text + "&sensor=false");
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
address = distanceX[0].InnerXml;
TextBoxPicAddress.Text = address;
}
}
JavaScript
<script type="text/javascript">
function submit() {
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx.cs/getadd",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
Markup
<asp:TextBox ID="TextBoxPicPostCode" runat="server"
CssClass="time"
onblur="submit();">
</asp:TextBox>
<asp:TextBox ID="TextBoxPicAddress" runat="server"
CssClass="address">
</asp:TextBox>
Make these changes
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<script type="text/javascript">
// change the function name from 'submit' here and at markup
function FetchAddress() {
//passing postalCode as string.
//Make sure that 'postalCode' is the parameter name at the webmethod
var dataValue = "{ 'postalCode' : '" + $('.time').val() + "'}";
//would be worthwhile to read about JSON.stringify, its the standard method
//var dataValue = JSON.stringify({ postalCode: $(".time").val() });
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx/getadd", // .cs is not required
data: dataValue,
contentType: 'application/json', //charset is not required
//dataType: 'json', // not required
success: function (result) {
var data = result.hasOwnProperty("d") ? result.d : result;
//alert("We returned: " + result.d);
// now we are assigning the return value to TextBoxPicAddress
$(".address").val(data);
}
});
}
</script>
Code-behind
//1. webmethod attribute required
[System.Web.Services.WebMethod]
//2. web methods should be static
//ref: http://encosia.com/why-do-aspnet-ajax-page-methods-have-to-be-static/
//3. return type string is needed
// because we need to fetch the return on the ajax callback
//4. we need to pass TextBoxPicPostCode as a parameter
// because we need to fetch the return on the ajax callback
public static string getadd(string postalCode)
{
string address = "No Address found!";
//_Address.InnerText = _PostCode.Text;
XmlDocument xDoc = new XmlDocument();
var remoteXml = "http://maps.google.com/maps/api/geocode/xml?address="
+ postalCode + "&sensor=false";
xDoc.Load(remoteXml);
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
address = distanceX[0].InnerXml;
}
return address;
}
At markup, change the event as onblur="FetchAddress();"
P.S: No time to type all the changes made in detail, so added as comment
.cs is Not Required
and
public void getadd()
Should be Static
so
[System.Web.Services.WebMethod]
public static void getadd()
JScript
<script type="text/javascript">
function submit()
{
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx/getadd",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
EDIT:
You Can't Use Controls Inside Static method. You nee to Refer This:
Using Jquery Ajax Call
Using AutoCompleteExtender
HTML
Javascript
`
function danish() {
var code = $("#<%=TextBoxPicPostCode.ClientID %>").val();
$.ajax({
type: "POST",
url: "GoogleAPI.aspx/getadd",
contentType: 'application/json; charset=utf-8',
data: '{code: "' + code + '"}',
dataType: 'json',
success: function (result) {
$("#<%=TextBoxPicAddress.ClientID %>").autocomplete({ source: result.d });
}
});
return false;
}
</script>`
Codebehind
using System.Web.Services;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
[WebMethod]
public static List<string> getadd(string code)
{
string address = "";
List<string> lst = new List<string>();
XmlDocument xDoc = new XmlDocument();
var jsonSerialiser = new JavaScriptSerializer();
try
{
HttpWebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
xDoc.Load(#"http://maps.google.com/maps/api/geocode/xml?address=" + code + "&sensor=false");
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
for (int i = 0; i < distanceX.Count; i++)
{
lst.Add(distanceX[i].InnerXml);
address = address + distanceX[i].InnerXml;
}
}
}
catch (Exception ex)
{
throw ex;
}
return lst;
}

Cast jsondata to NameValueCollection

I trying to pass JSON from jQuery to .ASHX file.
I want retrieve JSON data in .ASHX file by HttpContext and cats to NameValueCollection.
How do it?
$.ajax({
url: "GetLetterInformationHandler.ashx",
data: "{'Name':'david', 'Family':'logan'}",
contentType: "application/json; charset=utf-8",
type: "Get",
datatype: "json",
onSuccess: function (data) {
}
});
Now I can use the querystring and And cast as follows:
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
string cururl = context.Request.Url.ToString();
int iqs = context.Request.Url.ToString().IndexOf('?');
string querystring = (iqs < cururl.Length - 1) ? cururl.Substring(iqs + 1) : String.Empty;
NameValueCollection parameters = HttpUtility.ParseQueryString(querystring);
context.Response.ContentType = "text/plain";
}
I want use json insted of querystring
Try this:
$.map(data.d, function (item) {
return {
name: item.Name,
family: item.Family
};
})
Or if you want each function:
var resultData = data.d;
$.each(resultData, function() {
alert(this)
})
I have made some changes hope this will help you :)
Ajax function
$.ajax({
type: "POST",
url: "GetLetterInformationHandler.ashx",
data: "{'Name':'david', 'Family':'logan'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if( data != null){
if (data.msg == "SUCCESS"); {
alert( data.msg)
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
.ASHX file
public void ProcessRequest(HttpContext context)
{
string outputToReturn = String.Empty; // Set it to Empty Instead of ""
context.Response.ContentType = "text/json";
var getName = String.Empty ;
var getFamily = String.Empty ; // Make sure if the Particular Object is Empty or not
if (!string.IsNullOrEmpty(context.Request["Name"]))
{
getName = context.Request["Name"];
}
if (!string.IsNullOrEmpty(context.Request["Subject"]))
{
getFamily = context.Request["Subject"];
}
NameValueCollection nvc = new NameValueCollection();
nvc.Add(getName, getFamily);
var dict = new Dictionary<string, string>();
foreach (string key in nvc.Keys)
{
dict.Add(key, nvc[key]);
}
string json = new JavaScriptSerializer().Serialize(dict);
Console.WriteLine(json);
}

pass an array in jquery via ajax to a c# webmethod

I'd like to pass an array to a c# webmethod but don't have a good example to follow. Thanks for any assistance.
Here is what I have so far:
My array:
$(".jobRole").each(function (index) {
var jobRoleIndex = index;
var jobRoleID = $(this).attr('id');
var jobRoleName = $(this).text();
var roleInfo = {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
};
queryStr = { "roleInfo": roleInfo };
jobRoleArray.push(queryStr);
});
My ajax code
$.ajax({
type: "POST",
url: "WebPage.aspx/save_Role",
data: jobRoleArray,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
alert("successfully posted data");
},
error: function (data) {
alert("failed posted data");
alert(postData);
}
});
Not sure on the webmethod but here is what I'm thinking:
[WebMethod]
public static bool save_Role(String jobRoleArray[])
You will be passing an array of:
[
"roleInfo": {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
},
"roleInfo": {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
}, ...
]
And in my opinion, it would be easier if you have a class that matches that structure, like this:
public class roleInfo
{
public int roleIndex{get;set;}
public int roleID{get;set;}
public string roleName{get;set;}
}
So that when you call your web method from jQuery, you can do it like this:
$.ajax({
type: "POST",
url: "WebPage.aspx/save_Role",
data: "{'jobRoleArray':"+JSON.stringify(jobRoleArray)+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
alert("successfully posted data");
},
error: function (data) {
alert("failed posted data");
alert(postData);
}
});
And in your web method, you can receive List<roleInfo> in this way:
[WebMethod]
public static bool save_Role(List<roleInfo> jobRoleArray)
{
}
If you try this, please let me know. Above code was not tested in any way so there might be errors but I think this is a good and very clean approach.
I have implement something like this before which is passing an array to web method. Hope this will get you some ideas in solving your problem. My javascript code is as below:-
function PostAccountLists() {
var accountLists = new Array();
$("#participantLists input[id*='chkPresents']:checked").each(function () {
accountLists.push($(this).val());
});
var instanceId = $('#<%= hfInstanceId.ClientID %>').val();
$.ajax({
type: "POST",
url: "/_layouts/TrainingAdministration/SubscriberLists.aspx/SignOff",
data: "{'participantLists': '" + accountLists + "', insId : '" + instanceId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
}
In the code behind page (the web method)
[WebMethod]
public static void SignOff(object participantLists, string insId)
{
//subscription row id's
string[] a = participantLists.ToString().Split(',');
List<int> subIds = a.Select(x => int.Parse(x)).ToList<int>();
int instanceId = Convert.ToInt32(insId);
The thing to notice here is in the web method, the parameters that will receive the array from the ajax call is of type object.
Hope this helps.
EDIT:-
according to your web method, you are expecting a value of type boolean. Here how to get it when the ajax call is success
function AjaxSucceeded(result) {
var res = result.d;
if (res != null && res === true) {
alert("succesfully posted data");
}
}
Hope this helps
Adding this for the ones, like MdeVera, that looking for clean way to send array as parameter. You can find the answer in Icarus answer. I just wanted to make it clear:
JSON.stringify(<your array cames here>)
for example, if you would like to call a web page with array as parameter you can use the following approach:
"<URL>?<Parameter name>=" + JSON.stringify(<your array>)

asp.net web forms json return result

I use asp.net and web forms.
In my project I have asmx web service
[WebMethod]
public string GetSomething()
{
// avoid circual reference(parent child)
List<RetUsers> res = repo.GetAllUser().Select(c => new RetUsers {User_ID = c.User_ID,User_Name = c.User_Name,Date_Expire = c.Date_Expire }).ToList();
string res1 = res.ToJson();
// extension methods
return res.ToJson();
}
And result is in this format.
[
{"User_ID":1,"User_Name":"Test 1","Date_Expire":null},
{"User_ID":2,"User_Name":"Test 2","Date_Expire":null}
]
How can I append to label this result in $.ajax sucess to get this output:
1 - Test 1, 2 - Test 2.
Return the list instead, and use [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attribute - it will create JSON object as return automatically:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<RetUsers> GetSomething()
{
// avoid circual reference(parent child)
List<RetUsers> res = repo.GetAllUser().Select(c => new RetUsers {User_ID = c.User_ID,User_Name = c.User_Name,Date_Expire = c.Date_Expire }).ToList();
return res;
}
And on JS side:
$.ajax(
{
type: "POST",
async: true,
url: YourMethodUrl,
data: {some data},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg)
{
var resultAsJson = msg.d // your return result is JS array
// Now you can loop over the array to get each object
for(var i in resultAsJson)
{
var user = resultAsJson[i]
var user_name = user.User_Name
// Here you append that value to your label
}
}
})
public ActionResult MyAjaxRequest(string args)
{
string error_message = string.Empty;
try
{
// successful
return Json(args);
}
catch (Exception e)
{
error_message = e.Message;
}
}
what maybe the an error here

Resources