WebMethod access page control and set value - asp.net

My page name
public partial class AtamaGorevDegistir : System.Web.UI.Page
{}
My webmethod ajax side
var path = getLocation(location.href);
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
// data: "{" + str + "}",
contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
}
});
My webmethod
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string KisiBilgiDoldur(string KayitID, string TeklifID)
{
AtamaGorevDegistir atama = new AtamaGorevDegistir();
atama.AtananSuren.Value = "123";
return null;
}
But my problem my Control is null . But i can access this method but didnt set value and give error message. Why this happened?

WebMethod and ScriptMethod can't access the controls collection of the calling page. Think of it as outside the normal Web Forms lifecycle. When you use AJAX, you need to pass all data to the server side method it needs, and your server side should return all data that the client side needs. Then the client side should take that returned data and manipulate the DOM as necessary to display the result.
In your WebMethod, return the data instead of trying to assign it to a control, remove the return null;.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string KisiBilgiDoldur(string KayitID, string TeklifID)
{
return "123";
}
In your client side success handler, get the returned data and set the value of the control using JavaScript.
var path = getLocation(location.href);
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
// data: "{" + str + "}",
contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
//set control value to data.d here
}
});

You don't set the control value with a webmethod. Your return a value and from the api and do something with it, in the browser. Working with webmethods are not like webforms. The value you return in your webmethod is null... you're setting that null value into 'dd' in js, but you don't do anything with it. When you get your value back from the webmethod you need to do something with it. try 'alert(data.d)' in your success callback to see what i mean. Then $('#elm').text(data.d) if you want it on the page.

You should add parameters to data.
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
data:JSON.stringify({ KayitID: '1', TeklifID:'2' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
}
});

Related

Message":"Invalid web service call, missing value for parameter: \u0027fff\u0027.","StackTrace

i have a js file.a want to pass a value as a json using ajax to my codebehind but i get this error:
Message":"Invalid web service call, missing value for parameter: \u0027fff\u0027.","StackTrace
my javascript code is:
var values = { fff: "tttttttt" };
var uname = "fariddddddd";
$.ajax({
type: "GET",
url: "http://localhost:39787/Default.aspx/dataSave",
data: JSON.stringify(values),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
success: function (msg) {
AjaxSucceeded(msg);
},
error: function (msg) {
alert(msg);
}
});
my code behind is:
[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string dataSave(string fff)
{
string a = fff + "kazemi";
return a;
}
please help me
you are not enclosing the Key with quotes. change the declaration to like this. read this UnQuoted Object in javascript
var values = { "fff": "tttttttt" };

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

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.

JQuery and ASP.Net

Well im trying to return a more complex type than a string or bool but i fail what am i doing wrong?
JavaScript
<script language="javascript" type="text/javascript">
///<Reference Path="~/Script/jquery-1.3.2-vsdoc.js" />
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Test.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.Name);
},
failure: function() { alert("Failed") }
});
});
});
</script>
C# (This is not a webservice just a normal webpage)
[WebMethod]
public static ImageDC GetDate()
{
ImageDC dc = new ImageDC();
dc.Id = 1;
dc.Name = "Failwhale";
dc.Description = "Hurry the failwale is going to eat us!";
dc.IsPublic = true;
return dc;
}
I'm not sure what version .NET your running, but there is a breaking change with object returned from a web service. Check out this article.
http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
If you use fiddler to look at the request/response, it should be easy to tell if this is the problem.
http://www.fiddler2.com/fiddler2/
You should return a string.
return "dc = {Id:"+dc.Id+", Name:" + dc.Name +", Description: " +dc.Description + ", IsPublic: " +dc.IsPublic "}";

Resources