Call a web method from code behind in ascx page - c#

i have a script function that can call a web methods with two parameters.I want to call this script function from code behind.Here is my script function that i want to call from code behind.(I am using the .ascx usercontrol).
function BindApporment(obj, divid) {
debugger;
var username = "<%= Session["UserId"]%>";
var id = document.getElementById('<%=Hiddendocid.ClientID%>').value;
if (id != "") {
username = id;
}
$.ajax({
type: "POST",
url: "Dashboard.aspx/BindAppointment",
contentType: "application/json;charset=utf-8",
data: "{'date':'" + obj + "',userid:'" + username + "'}",
dataType: "json",
success: function (data) {
$(divid).html(data.d);
},
error: function (result) {
alert("Error ");
}
});
}
here is my web method
[WebMethod]
public static string BindAppointment(DateTime date, string userid)
{
}
...I want to call the script function BindApporment() from code behind..i have already tried a lot of code but this is not working..
I have tried these code but not working:
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "BindApporment", "<script>BindApporment(" + date.AddDays(k).Date + "," + ddldoc.SelectedValue + ");</script>");
any suggestions??

You are trying to do that is not applicable to to in ASP.NET structure. A ascx control cannot process request. The ASCX can work with the data send via postbacl
You need to create ASMX service and query it with ajax request you have. How to let an ASMX file output JSON

Related

jquery ajax with query string invoking at server side not working

In my application I have used jquery ajax and this ajax call invokes some method at server side. In this method I have code which grabs the query strings and based on the query string value it processes the data. I am using below lines of code to get query string.
var MyajaxCall = function () {
$.ajax(
{
type: "POST",
url: "OneCol.aspx/SingleData",
data: JSON.stringify({DptID:1}),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (msg) {
jsonData = msg.d;
},
Error: function (x, e) {
alert("Some error");
}
});
};
C# code
[WebMethod]
public static string SingleData(string DptID)
{
OneTestPage onpage = new OneTestPage ();
return onpage.GetString();
}
private string GetString()
{
return Request.QueryString["test"].ToString();
}
Everytime my ajax request hits this line of code I am getting "Request is not available in this context". Is this because data is not ready yet this time ? if so what is the best way to get it work.

Calling a method with ajax in aspx.cs from aspx

I am trying to call a method from my aspx page. This method is found on the aspx.cs page, but it is throwing an error. Do you know what's wrong, please?
ajax script
<script type="text/javascript">
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
} //Default.aspx
function insertMarker() {
var usernameName = 'username';
var usernameVal = document.getElementById('<%=hdnUsername.ClientID%>').value;
var latitudeName = 'latitudeStr';
var latitudeVal = document.getElementById('<%=hdnMarkerLatitude.ClientID%>').value;
var longituteName = 'longitudeStr';
var longitudeVal = document.getElementById('<%=hdnMarkerLongitude.ClientID%>').value;
var iconName = 'markerIcon';
var iconVal;
if (document.getElementById('blueMarker').checked) {
iconVal = 'images/blueMarker.png';
}
if (document.getElementById('greenMarker').checked) {
iconVal = 'images/greenMarker.png'
}
if (document.getElementById('pinkMarker').checked) {
iconVal = 'images/pinkMarker.png';
}
var titleName = 'name';
var titleVal = document.getElementById('<%=title.ClientID%>').value;
var descriptionName = 'description';
var descriptionVal = document.getElementById('<%=description.ClientID%>').value;
$.ajax({
type: "POST",
url: "mapping.aspx/insertNewMarker",
data: {"username" : usernameVal, "longitudeStr":longitudeVal, "latitudeStr" :latitudeVal, "markerIcon":iconVal, "name" : titleVal, "description" :descriptionVal},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
Website Design
Save Marker
Title
Description
Save
Aspx.cs Method.
[ScriptService]
public partial class mapping: System.Web.UI.Page
{
[WebMethod]
private static void insertNewMarker(string username, string longitudeStr, string latitudeStr, string markerIcon, string name, string description)
{
//My Code
}
}
Your server-side webmethod cannot be private, you have to change it to public.
From MSDN documentation on webmethods:
When you create a Web service in managed code, you indicate the
methods that are available through that Web service by placing the
WebMethod attribute before the method declaration of a Public method.
Private methods cannot serve as the entry point for a Web service
although they can be in the same class and the Web service code can
call them.
Change your data like this
data:JSON.stringify({username : usernameVal, longitudeStr:longitudeVal, latitudeStr :latitudeVal, markerIcon:iconVal, name : titleVal, description :descriptionVal}),
You need to pass data as json stirng which has a specific format. If you use JSON.stringify data will be convetred to json string and if you don't use this than you have to pass every paremter and its value in quotes like this.
data:"{username:'" + usernameVal + "',............}",

Can we call User control code behind method using Jquery ajax?

I'm trying to do something, Can we call User control code behind method using Jquery ajax ?
likes:
ASCX CODE:
<script type="text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Uploads.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
ASCX.CS
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
But its will create an error please can any one what do i am wrong.
The user control doesn't have all the functionality of a page and can't be called directly.Check out the following link for complete solution
Creating a Page method (ScriptMethod) within an ASCX user control using AJAX, JSON, base classes and reflection

jQuery AJAX call to an ASP.NET WebMethod

I have the following jQuery AJAX request:
function sendUpdate(urlToSend) {
var code = AccessCode;
var url = urlToSend;
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "webmethods.aspx/UpdatePage",
data: "{ accessCode: " + code + ", newURL: '" + url + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
And the corresponding ASP.NET WebMethod:
[WebMethod]
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try
{
HttpContext.Current.Cache[accessCode + "l"] = newURL;
}
catch
{
result = false;
}
return result;
}
That all used to work correctly with "async:false", however I have to get rid of it as it freezes the browser until the response is received. Now the AJAX request above returns "undefined".
Could anybody tell me why it happens and where the problem is?
Thanks.
You should really make sure to properly encode this JSON. JSON.stringify is the most reliable method:
data: JSON.stringify({ accessCode: code, newURL: url })
This ensures that even if the code and url variables contain some dangerous characters that will break your string concatenations in the resulting JSON at the end everything will be properly encoded. The JSON.stringify method is natievly built into modern browsers but if you need to support legacy you could include json2.js.
Also because you code is no longer blocking you should make sure that if you call this sendUpdate from some button click or form submit you cancel the default action by returning false.
My way works correctly:
[System.Web.Services.WebMethod()]
public static string getHello(string str)
{
//do some things with str
return str;
}
In file .js, I define this function to call webmethod in file .cs:
function CallServerFunction(StrPriUrl, ObjPriData, CallBackFunction) {
$.ajax({
type: "post",
url: StrPriUrl,
contentType: "application/json; charset=utf-8",
data: ObjPriData,
dataType: "json",
success: function (result) {
if (CallBackFunction != null && typeof CallBackFunction != 'undefined') {
CallBackFunction(result);
}
},
error: function (result) {
alert('error occured');
alert(result.responseText);
window.location.href = "FrmError.aspx?Exception=" + result.responseText;
},
async: true
});
}
Then, call to use (call in file.js):
var text = $("#textbox_send").val();
var myresult;
CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: text }), function (myresult) {
if (text != "")
$('#' + id).append('<p>' + $("#account_user").text() + ': ' + myresult.d + '</p>');
});
The "undefined" could be the result of a server error.If you use Firebug,Firefox(or any good client debugging tool), you can find the error returned by the server. Paste the error,if any.
Nevertheless, I also noted the the "data" for "accessCode" is not properly enclosed within quotes ‘ ’
The corrected data option would be :
data: "{ accessCode: '" + code + "', newURL: '" + url + "' }",
PS:
Since 'options' have a different meaning in Jquery, I would recommend changing the variable name as 'setting' . Change 'var options ' to 'var settings'. :)

relative path to consume local asmx

In my asp.net webapp I'm using a local webservice to retrieve data's. The system is in a popup (wich is an another page in fact)
So here's the jquery code:
$(document).ready(function () {
$('#ddlToBind').change(function () {
var parameter = "{'aId':'" + $("#ddl").val() + "'}";
$.ajax({
url: "../WebServicesASMX/PMywebserv.asmx/Test",
data: parameter,
dataType: "json",
type: "POST",
contentType: "application/json",
success: function (data) {
$('#ddlToBind>option').remove();
for (var i = 0; i < data.d.length; i++) {
$("#ddlToBind").append("<option value='" + data.d[i].Id + "'>" + data.d[i].Name + "</option>");
};
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
It is working good while you are in the root of site and once you launch the script in other pages the path is not correct so asmx is not reached..
I've tried with the tilde "~" in place of ../ but it doesn't work.. url: "~/WebServicesASMX/PMywebserv.asmx/Test"
Is it a possibility to specify relatives path in my jquery script?
VirtualPathUtility to the rescue!
url: "<%= VirtualPathUtility.ToAbsolute("~/WebServicesASMX/PMywebserv.asmx/Test") %>",
See this post by Rick Strahl: http://www.west-wind.com/weblog/posts/2009/Dec/21/Making-Sense-of-ASPNET-Paths
Note that for this to work the script needs to be in a page that is processed by ASP.NET e.g. aspx, ascx, MVC View. If your script is in a plain js file, you'll need to move it, or reference a javascript global variable that you define elsewhere in ASP.NET code.
use
<%= ResolveUrl("~/WebServicesASMX/PMywebserv.asmx/Test") %>

Categories