pass an array in jquery via ajax to a c# webmethod - asp.net

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>)

Related

Passing parameters in ajax call

I'm trying to make an ajax call to the controller method. without parameter it works fine. Once i add the parameter i always receive a null parameter to the cotroller. I think i have correctly done the parameter passing in ajax call.
<script type="text/javascript">
$(document).ready(function () {
$('#lstStock').change(function () {
var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>';
var dropDownID = $('select[id="lstStock"] option:selected').val();
alert(dropDownID); // here i get the correct selected ID
$.ajax({
type: "POST",
url: serviceURL,
data: '{"stockID":"' + dropDownID + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data.Result);
}
function errorFunc() {
alert('error');
}
})
});
</script>
Controller:
[HttpGet]
public ActionResult GetStockPrice()
{
return View();
}
[HttpPost]
[ActionName("GetStockPrice")]
public ActionResult GetStockPrice1(string stockID)//I get the null parameter here
{
DeliveryRepository rep = new DeliveryRepository();
var value = rep.GetStockPrice(stockID);
return Json(new { Result = value }, JsonRequestBehavior.AllowGet);
}
It's because you are treating the data as a string
data: '{"stockID":"' + dropDownID + '"}',
you can change it to:
data: { stockID: dropDownID },
in some cases, depending on the parameter declared in your controller method, you need to serialize the data. If you need to do that then this is how you would do it:
var o = { argName: some_value };
$.ajax({
// some other config goes here
data: JSON.stringify(o),
});
try data: { stockID : dropDownID},
$('#lstStock').change(function () {
var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>';
var dropDownID = $('select[id="lstStock"] option:selected').val();
// $(this).val(); is better
alert(dropDownID); // here i get the correct selected ID
$.ajax({
type: "POST",
url: serviceURL,
data: { stockID : dropDownID},
....
Try specifying:
data: { stockID : dropDownID },
It looks like you're passing up "stockID" not stockID.
A good tool to use for this is Fiddler, it will allow you to see if the Controller action is hit and what data was sent upto the server.

Using Ajax in a .net project to call a .aspx.cs function NOT WORKING

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 ";
}

How to consume the return value of a webservice in jquery ajax call?

I have a simple webservice in asp.net which determine if the input parameter is valid or not :
[WebMethod]
public bool IsValidNationalCode(string input)
{
return input.IsNationalCode();
}
I call it from an aspx page by jquery ajax function :
$('#txtNationalCode').focusout(function () {
var webMethod = "../PMWebService.asmx/IsValidNationalCode";
var param = $('#txtNationalCode').val();
var parameters = "{input:" + param + "}";
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if(msg.responseText == true)
$('#status').html("Valid");
else {
$('#status').html("Invalid");
}
},
error: function () {
$('#status').html("error occured");
}
});
});
But I don't know how to get the return value of webservice in order to show appropriate message . Here if(msg.responseText == true) doesn't work
Make the IsValidNationalCode method static and use this in javascript:
success: function (msg) {
if (msg.d == true)
$('#status').html("Valid");
else {
$('#status').html("Invalid");
}
}
For "d" explanation follow this link: Never worry about ASP.NET AJAX’s .d again

2 page methods on an aspx page

I'm calling a page method with jquery and it works just fine. I'm creating a second one and it's not working at all; all I get is the error function. Is it possible to put more than 1 page method in an aspx page?
Here's my jquery on the client:
function LoadCount() {
var TheObject = $.toJSON(CurrentForm);
var TheParameter = "{'TheParameter' : '" + TheObject + "'}";
$('#testobj').html("loading");
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetCount",
data: TheParameter,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
function successFn(thedata) { $('#result').html(thedata.d); };
function errorFn() { alert("problem getting count"); };
function LoadData() {
var ConfirmLoad = "test";
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetLoaded",
data: ConfirmLoad,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successLoad,
error: errorLoad
});
};
function successLoad(thedata) { alert((thedata.d)); };
function errorLoad() { alert("problem getting loaded"); };
And on the server side, I have this:
[WebMethod]
public static string GetCount(string TheParameter)
{
// some code
return JsonResult;
}
[WebMethod]
public static string GetLoaded(string ConfirmLoad)
{
return "test string";
}
LoadCount and GetCount work great, I thought I'd copy the implementation to create another page method but the second time, nothing good happens. Thanks for your suggestions.
You need to set dataType: "text" in the $.ajax() call properties if you're just returning plain text instead of a JSON encoded string.
You might also want to leave the contentType unspecified (at the default value of 'application/x-www-form-urlencoded') if your're sending plain text instead of a JS object.

spring.net + nhibernate + jquery ajax call to webmethod at codebehind

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();

Resources