This question already has answers here:
Pass a user defined object to ASP.NET Webmethod from jQuery, using JSON
(2 answers)
Closed 4 years ago.
I am trying to pass an object to a page method defined. I'm trying to pass data to it collected from three textboxes.
Page Method
[System.Web.Services.WebMethod]
public static string saveDataToServer(object csObj)
{
// Function Body.
}
Javascript/jQuery
$("#osmSendMsg").click(function () {
debugger;
var cntDetails = {
cntName : $("#osmContactName").val(),
cntEmail : $("#osmContactEmail").val(),
cntMsg : $("#osmContactMessage").val()
}
PostDataToServer(cntDetails,"Please wait...","/ContactUs.aspx/saveDataToServer","csObj");
});
PostDataToServer
// Post data to server (ajax call).
function PostDataToServer(dataToSend, strMessagetoShow, strMethodToCall, jsonObjectName) {
debugger;
/*
dataToSend Contains the JSON Object.
submitType 1 == Normal Submit; 2 == Submit and Print.
strMessagetoShow Text that is displayed in the Please Wait Window.
*/
var tempurl = strMethodToCall;
var tempdata;
$.ajax({
url: tempurl,
type: "POST",
async: false,
dataType: "json",
data: "{" + jsonObjectName + ":" + JSON.stringify(dataToSend) + "}",
//timeout: 30000,
contentType: "application/json; charset=utf-8",
success: function (data) {
tempdata = data;
},
error: function (result) {
tempdata = null;
}
}); //end of the ajax call
return tempdata;
} //End of the post Data
Now the call is reaching the web method. No problem. I'm getting the object as well.But how do I process the object?
As you can see, that's what I'm getting. I also tried declaring a class and passing it as the parameter..but all it's properties are empty. If you notice the data is appearing as a key, value pair. I could convert it into a Dictionary, but I believe that's a complicated solution.
A simpler solution would be welcomed!
Your result collection is being returned in the 'data' parameter of your success method. You can simply process this parameter directly like data[0].cntName.
As you are able to reach your webmethod, you need to modify your webmethod to read the data from the object as follows:
[System.Web.Services.WebMethod]
public static string saveDataToServer(Dictionary<string, string> csObj)
{
try
{
string Name = csObj["cntName"].ToString();
string Email = csObj["cntEmail"].ToString();
//you can read values like this and can do your operation
return "";//return your value
}
catch(Exception ex)
{
throw new Exception(Ex.Message);
}
}
Related
I am using .NET MVC4
I have used javascript function as below:
function ShowDomainComponentDetail(compCode) {
alert(compCode);
$.ajax({
url: "/PP/getDomainComponentDetailWithDomain",
data: {
'ComponentCode': compCode
},
dataType: "json",
type: 'POST',
cache: false,
success: function (_responseData) {
$('#divShowDomainCompDetail').show();
alert(_responseData.Data)
},
error: function () {
//
}
});
}
Upon success I am getting list in .net as:
IdObservation=1, ObservationName="Started" , ObsType="Announced";
IdObservation=2, ObservationName="Not Started" , ObsType="Un Announced";
IdObservation=3, ObservationName="Declared" , ObsType="Announced";
My problem is i am not abl;e to access this list inside Ajax sucess block.
How can i access this list as:
alert(_responseData.IdObservation);
alert(_responseData.ObservationName);
(Further i am going to assign this to labels).
Please help me.
EDIT 1 :
My Serverside Function returning list:
public JsonResult getDomainComponentDetailWithDomain(string ComponentCode)
{
try
{
List<TEAMS_PP.Entity.correlations> compDetail_list = new correlation().getDomainComponentDetailswithDomain(ComponentCode);
return Json(compDetail_list);
}
catch (Exception)
{
List<TEAMS_PP.Entity.correlations> BlankList = new List<TEAMS_PP.Entity.correlations>();
return Json(BlankList);
}
}
Use index with data object like below:
alert(_responseData[0].IdObservation);
loop through object and get values for each object.
you can use the $each to iterate it
$.each(_responseData, function (key, value) {
var arr = value.IdObservation;
});
I am calling an asmx webservice which returns json (msg.d) that is consumed properly by knockout.js. When I attempt to return the identical json to asmx, I get error messages. Is there something obvious I'm missing? ... msg.d is a well formed object array.
calling storeGroupCategories(msg.d); returns webservice error ...
{"Message":"Invalid JSON primitive: Baby+Books."
calling storeGroupCategories(msg); returns webservice error ...
{"Message":"Invalid JSON primitive: d."
WebService
public class kbo_inexcludecategories : WebService
{
[WebMethod]
public List<Group> GetIncludeExcludeJson()
{
var Groups = new List<Group>();
ShopAssistGroupHandler.getInExCategories(Groups);
return Groups;
}
[WebMethod]
public GroupGuid StoreGroupCategories(List<InExCategory> inExCategories)
{
var inExString = JsonConvert.SerializeObject(inExCategories);
var returnGuid = DataHandler.SaveGroupJsonString(inExString);
return new GroupGuid(returnGuid);
}
}
Associated json ...
var _url = "kbo-inexcludecategories.asmx/";
var _method = "GetIncludeExcludeJson";
var _jsonData = "{}";
function storeGroupCategories(groupCategories) {
if(groupCategories != ""){
showProgressBar("Storing Group Categories");
getJsonData(_url, "StoreGroupCategories", groupCategories);
}
}
function getGroupMatrix() {
showProgressBar("Loading Group Categories");
getJsonData(_url, _method, _jsonData);
}
function getJsonData(url, method, jsonData) {
var myUrl = url + method;
$.ajax({
type: "POST",
url: myUrl,
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, //blocks window close
success: onSuccess,
error: onError
});
}
function onSuccess(msg) {
// Hide the fake progress indicator graphic.
hideProgressBar("");
if(msg.d.hasOwnProperty("Guid")) {
saveGroupGuid(msg.d);
}
else {
storeGroupCategories(msg.d);
//showGroupAccordion(msg.d);
//OpenAdvancedDialog();
}
}
json sample ...
"{\"groups\":[{\"__type\":\"group\",\"id\":1488,\"name\":\"Baby Books\",\"categories\":
[{\"__type\":\"groupcategory\",\"id\":152,\"name\":\"Activity Books\",\"value\":\"Included\"},
{\"__type\":\"groupcategory\",\"id\":167,\"name\":\"Bedtime and Dreams\",\"value\":\"Excluded\"}
To begin with I think you need to pass your json in like this:
storeGroupCategories(msg.d)
But within this function you also need to create valid json parameters to the post, which would look like this:
getJsonData(_url, "StoreGroupCategories", "{ inExCategories: " + groupCategories + " }");
I would also change your signature to the following, so groups matches the argument you are passing across:
public GroupGuid StoreGroupCategories(List<InExCategory> groups)
If you put a break point in the web page method, you will see exactly what is coming across, and check that it is what you are expecting.
I was looking on internet for over 2 hrs now, trying to find simple example of how to fill jQuery Variable from serverside code on load of asp.net page.
What i have so far:
I have a button which call this jquery code:
function GetListOfQuestions() {
$.ajax({
type: "POST",
url: 'UserProfile.aspx/getQuestions',
contentType: "application/json; charset=utf-8",
dataType: "json",
error: OnAjaxError,
success: AjaxSucceeded
});
//$.getJSON('UserProfile.aspx/getQuestions', {}, function (data) {
// alert(data);
//});
}
function AjaxSucceeded(result) {
alert(result);
}
GetListOfQuestions calls serverside :
[WebMethod]
public static List<Question> getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return list.ToList();
}
result return an object if I alert it, so it must contain some kind of data, but I can't find any example of how I can retrieve data again on client side.
I'm not sure if what I am doing right now is right at all (I'm new to jQuery). So how can I retrieve data from result variable again?
There could be better ways but this is one way I know of:
[WebMethod]
public static string getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return new JavaScriptSerializer().Serialize(list.ToList())
}
In your jQuery method, you can
result = $.parseJSON(data) ;
Do a console.log(result) to see how to iterate through result, should be just a for loop.
Put a hidden field on your page an set the variable value there, later read the hidden value from js.
Another option is to use ScriptManager.RegisterStart UpScript to write your variable directly as js to the page.
This question already exists:
Closed 10 years ago.
Possible Duplicate:
How To Return Value From Code Behind To AJAX?
This is my AJAX code
$.ajax({
type: 'POST',
url: 'country_management.aspx/save',
cache: false,
data: "{'parameter':'paramValue'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
if (data.d == "error") {
$('.success_box').hide();
$('.error_box').show();
}
else {
$('#name').val('');
$('.error_box').hide();
$('.success_box').show();
}
}
});
Code Behind:
[WebMethod]
[ScriptMethod]
public static string save(string parameter)
{
string name = HttpContext.Current.Request.QueryString["name"].Trim();
return "error";
}
after writing the first line, return statement does not return anything to the AJAX.
Without knowing the context of the whole application is kind of difficult to answer your question. (Does name get supplied from elsewhere in the app, you could make use of a session?)
But what is stopping you from passing the name through in the ajax call? Rather than just sending through'parameter':'paramValue'.
You have to remember your query string is supposed to contain the parameter you're looking for. at the moment it's looking something like.
http://www.somesite.com/country_management.aspx/save?parameter=paramValue
when you actually need
e.g.
http://www.somesite.com/country_management.aspx/save?parameter=paramValue&name=newName
Javascript
$.ajax({
type: 'POST',
url: 'country_management.aspx/save',
data: { parameter:'paramValue', name: 'newName'},
success: function (data) {
//do something with the response
}
});
Codebehind
[WebMethod]
[ScriptMethod]
public static string save(string parameter, string name)
{
PerformSave(name, parameter);
return "Data Saved!";
}
TIP
Try out this app. Fiddler. It's extremely useful when you're working with things like ajax calls etc. Actually any web development. :)
Because you didn't post any field or property "name"
If you do the ajax after clicked in a button inside form, data will be the form serialized.
Another thing is, why should you expect "name" var in query string, I don't see any url with aspx?name="any name"
Inside my controller there is JsonResult action which returns me a list of House object.
I want onclick using ajax to retrieve these data and to display json data inside my view.
Inside firebug I'm able to see proper Response and Json result but I dont know how to display inside my view.
function GetTabData(xdata) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id: xdata }),
success: function (result) {
// tried with these but it doesnt work
// result = jQuery.parseJSON(result);
// alert(result.Title);
},
error: function () { alert("error"); }
});
}
public JsonResult GetTabData()
{
...
var temp = getMyData...
return Json(temp, JsonRequestBehavior.AllowGet);
}
// View page
<div id="showContent">
// Json data should appear here
</div>
Inside firebug JSON tab when success:function(result) is empty
I have following data:
Id 149
PropertyType "Apartment"
StreetNumber "202B"
CityName "Sidney"
Title "My test data"
success: function (json) {
var data = null;
$.each(json.items,function(item,i){
data = '<div>'+item.Id+ ' ' + item.CityName +'</div>';
$("#showContent").append(data);
});
}
First of all, you can specify the dataType attribute in your ajax call to 'json' and then don't have to decode the json response again -
dataType: 'json'
Then, you don't need to use parseJSON. Simply use result.Title etc.
success: function (result) {
alert(result.Title);
var showContent = $('#showContent');
showContent.html(result.Id+','+result.Title);
},
EDIT: As Mukesh said, you can have the ajax function return json without using any extra decoding.
The ajax call result is already an object. You can do whatever you want with it it inside the success function.
For example you could create a table of the information dynamically inside the function, or send the data to another function by calling the function inside that success function. Once you leave the success function, the data is not usable anymore.
Access the data object like any object (data.someProperty).