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
Related
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.
I think it might be configuration issue but i cannot figure it out why I am able to make a call from ajax if contentType is "Json" but if i change it to xml it does not call that webmethod. Can someone Please help.
Below code is not working.
In JavaScript
$.ajax({
type: "POST",
dataType: "xml",
contentType: "application/xml; charset=utf-8",
url: "Test.aspx/GenerateXML",
success: function (result) {
alert(result)
},
error: function (error, e1, e2) {
alert(error);
}
});
C# in aspx.cs page
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml, UseHttpGet = false, XmlSerializeString = true)]
public static DataTable GenerateXML()
{
TestCalculator testCalculator = new TestCalculator();
DataTable dataTable = new DataTable();
dataTable = testCalculator.GetValue("Test");
return dataTable;
}
Working Code
In JavaScript
$.ajax({
type: "POST",
dataType: "Json",
contentType: "application/Json; charset=utf-8",
url: "Test.aspx/GenerateXML",
success: function (result) {
alert(result)
},
error: function (error, e1, e2) {
alert(error);
}
});
C# Code
[WebMethod]
public static DataTable GenerateXML()
{
TestCalculator testCalculator = new TestCalculator();
DataTable dataTable = new DataTable();
dataTable = testCalculator.GetValue("Test");
return dataTable;
}
Im using Ajax in a .net project (isn't MVC.net). I want to call a function of my .aspx.cs from a JScript Function.
This is my JScript code:
$("a#showQuickSearch").click(function () {
if ($("#quick_search_controls").is(":hidden")) {
$.ajax({
type: "POST",
url: "Default.aspx/SetInfo",
data: "{showQuickSearch}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
}
});
$("#quick_search_controls").slideDown("slow");
$("#search_controls").hide();
$("#search").hide();
} else {
$("#quick_search_controls").hide();
}
});
And this is my .aspx.cs Function:
[WebMethod]
public string SetInfo(string strChangeSession)
{
Label1.Text = strChangeSession;
return "This is a test";
}
The problem is that my .aspx.cs function is not being called and isn't updating the label.text.
Try making your function static.
[WebMethod]
public static string SetInfo(string strChangeSession)
{
//Label1.Text = strChangeSession; this wont work
return "This is a test";
}
data: "{showQuickSearch}" is not valid JSON.
Here's how a valid JSON would look like:
data: JSON.stringify({ strChangeSession: 'showQuickSearch' })
Also your PageMethod needs to be static:
[WebMethod]
public static string SetInfo(string strChangeSession)
{
return "This is a test";
}
which obviously means that you cannot access any page elements such as labels and stuff. It is inside your success callback that you could now use the result of the PageMethod to update some label or whatever.
$.ajax({
type: "POST",
url: "Default.aspx/SetInfo",
data: "{'strChangeSession':'showQuickSearch'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
},
error: function (xhr, status, error) {
var msg = JSON.parse(xhr.responseText);
alert(msg.Message);
}
});
And your backend code:
[WebMethod]
public static string SetInfo(string strChangeSession)
{
return "Response ";
}
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>)
I am trying to make a jquery ajax call to a static method on the codebehind file. The problem is that ArtistManager injected by Spring is not static and I cannot use it in the static webmethod. I am looking for any ideas on how to implement this
ArtistList.aspx
$(document).ready(function () {
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "ArtistList.aspx/GetArtists",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#Result").text(msg.d);
alert("Success: " + msg.d);
},
error: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
alert("Error: " + msg.d);
}
});
});
});
ArtistList.aspx.cs
private IArtistManager artistManager;
public IArtistManager ArtistManager
{
set { this.artistManager = value; }
get { return artistManager; }
}
protected long rowCount = 0;
.
.
.
[WebMethod]
public static IList<App.Data.BusinessObjects.Artist> GetArtists()
{
//return ArtistManager.GetAll("Name", "ASC", 1, 100, out rowCount);
}
Assuming a single context, in which an IArtistManager is configured named artistManager:
using Spring.Context.Support;
// ...
[WebMethod]
public static IList<App.Data.BusinessObjects.Artist> GetArtists()
{
IApplicationContext context = ContextRegistry.GetContext(); // get the application context
IArtistManager mngr = (IArtistManager)context.GetObject("artistManager"); // get the object
return mngr.GetAll("Name", "ASC", 1, 100, out rowCount);
}
Note that this code won't compile either, since rowCount is an instance member, similar to artistManager in your question.
Don't know about spring, but I am sure it has something like structure map.
ObjectFactory.GetInstance<IAristManager>.GetAll();