Update markup dynamically after JS Ajax call to CodeBehind static function - c#

I'm using $.ajax({...}); to send some data to my server (the aspx's CodeBehind file in c#). In order to receive this data to work with in the CodeBehind file, I have to use a static WebMethod ([System.Web.Services.WebMethod]). Once I work with this data, I want to either redirect them to a new page if there was a success (In my case, a successful credit card charge), otherwise, send an alert to the user that something went wrong (i.e., credit card charge randomly didn't work).
Is there a way to access/alter the current page's markup via this static WebMethod (e.g., add <script>alert("Something went wrong")</script>), without the ability to use asp page controls? (i.e., this which is the page in non-static methods in CodeBehind files)

You may need to use Success and Failure section of $.ajax syntax. Please refer an example below. I hope your web method returns string to make this work.
Sample WebMeethod
[ScriptMethod()]
[WebMethod]
public static string YourWebMethod()
{
String yourMessageString = String.Empty;
//process as per your logic
yourMessageString = "Some Message";
return yourMessageString;
}
$.ajax({
type: "POST",
url: "/yourpage.aspx/yourwebmethod",
async: false,
contentType: "application/json; charset=utf-8",
data: "your data",
dataType: "json",
success: function (message) {
alert(message);
},
error: function () {
alert("error");
},
failure: function () {
alert('failure');
}
});

Related

How to call a UserControls CodeBehind method from Jquery in ASP.NET?

Iam having a UserControl for showing Success/Warning/Error message. For all these kind of messages we have one UserControl "Message.ascx" Currently using for other aspx pages without Jquery
As we are trying to maintain standard message alerts.
Now as iam using Jquery and JSON calls in my aspx page for the first time., i want to show these success message from my jquery.,
In general aspx codebehind i have used the User control as
//register User Control
<UM1:UM runat="server" ID="Message" />
....
public void insert(){
.. Some logic.., after success
Message.ShowSuccess(" Inserted Successfully");
}
But here in Jquery how do i call these ShowSuccess() which is in ascx.cs
my ajax call
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Voyage.aspx/Context_Update",
data: "{'ID':''1}",
dataType: "html",
success: function (html) {
try {
// Want to Show Message.ShowSuccess(" Inserted Successfully");
} catch (ex) {
alert("ErrCode:1");
}
Iam not getting any idea and have not found any results too..,
Please help me out
You can't make a call to a User-Control in ASP .NET as it isn't something that is directly served to the outside world but instead something that the server combines into your page during the page life-cycle.
If you want to call something on the server you need to add the [WebMethod] attribute to the server side method, this allows you to call from jQuery. You could have a [WebMethod] on your page that then calls some code in your User-Control, but not directly access your User-Control.
So, something like this:
MyPage.aspx
[WebMethod]
public static string GetMessageFromWebPage()
{
return MyUserControl.GetMessageFromUserControl();
}
MyUserControl.ascx
public static string GetMessageFromUserControl()
{
return "Hello World!"
}
jQuery
$.ajax({
type: "POST",
url: "MyPage.aspx/GetMessageFromWebPage",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something with the page method's return.
$("#Result").text(msg.d);
}
});

How can I call a method that are in my code-behind via Javascript or Jquery

I have the follow line in my Javascript code
credenciadausuario = '<%= getCredenciada() %>';
In my code-behind I have this method
public string getCredenciada()
{
Utilidade.QuebraToken tk = new Utilidade.QuebraToken();
string credenciada = tk.CarregaToken(1, Request.Cookies["token"].Value);
return credenciada;
}
but when I put the debugger in my javascript code, the credenciadausuario variable, receives the string "<%= getCredenciada() %>" and not the return of my method. How can I call my method that are in my code-behind via javascript or jquery ?
It seems all you want to do in your code is get the value of a cookie. Why not do that in JavaScript on the client?
IF possible make use of ajax and do call the method, that will do you task.
check this post : http://pranayamr.blogspot.com/2012/01/calling-server-side-function-from.html
Cs File (codebehind)
[WebMethod]
public static string IsExists(string value)
{
//code to check uniqe value call to database to check this
return "True";
}
Javascript
function IsExists(pagePath, dataString)
{
$.ajax({
type:"POST",
url: pagePath,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
},
success:
function(result) {
alert( result.d);
}
}
});}
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'ab" }";
IsExists(pagePath, dataString);
This article from Encosia is excellent. It shows how to call a method in your code behind using jQuery ajax.
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
In your code behind you have to give the method the [WebMethod] attribute:
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
To call that method using jQuery you would use the following:
$.ajax({
type: "POST",
url: "PageName.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Well, to actually CALL your code-behind methods from Javascript, you would have to use ajax. JQuery has a nice $.ajax wrapper for that.
But I think you just want to include some value into the js code once, while it's being generated and sent to the browser. In that case, you need to use a file type which ASP.NET recognizes as a dynamic file.
The easiest would be to put JS code (in a <script> tag) into .ascx files. Then <%= getCredenciada() %> will be executed and will return an actual string which will be rendered into javascript code.
Then, of course, you should include such a control to the page as a regular ASP.NET control.
And I am not saying this is the best way to achieve what you want. Sometimes it's just the fastest.

Sending variable to a C# inside Javascript code

Javascript Code:
function jsfunction ()
{
var sayi = 9999;
alert('<%= cfunction("'+sayi+'")%>');
}
C# Code:
public string cfunction(string gelen)
{
return gelen;
}
Normally,There is should be 9999 value which is send to C# code from javascript code,but,this value returning as '+sayi+'.
Also,that's gives me alert 9999.What am I wrong?
By the time JavaScript runs, the C# code has already been executed. Learn you page life cycle.
If you want to call a serverside function to get data, you need to learn about Ajax.
C# (server-side) can generate markup for client side, client side can't call back up to server-side without some kind of Ajax type web request.
To do what you're looking for you can create a C# webmethod
[WebMethod()]
public static string cfunction(string gelen)
{
return gelen;
}
And consume the webmethod with a client-side jQuery.ajax() method (You'll need the jQuery library script if you don't have it already)
function jsfunction() {
var sayi = 9999;
$.ajax({
type: "POST",
url: "YOUR-ASPX-PAGE.aspx/cfunction",
data: "{gelen:'" + sayi + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
}
You can use scriptmethod attribute to invoke server side method from your javascript code. But you must understand the mechanism behind it so that u can debug and modify accordingly.
http://www.chadscharf.com/index.php/2009/11/creating-a-page-method-scriptmethod-within-an-ascx-user-control-using-ajax-json-base-classes-and-reflection/

Using jQuery AJAX to call ASP.NET function in control code-behind instead of page code-behind

I have a user control that I'm creating that is using some AJAX in jQuery.
I need to call a function in the code-behind of my control, but every example I find online looks like this:
$("input").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
//do something
}
});
});
This works fine if I have the method in the Default.aspx page. But I don't want to have the function there, I need the function in the code-behind of my control. How can I modify the url property to call the correct function?
I tried:
url: "GetResult"
but that didn't work.
The way to handle this is to have the webmethod in your page, then just pass the values directly to a control method with the same signature in your control - there is no other way to do this.
In other words, ALL the page method does is call the usercontrol method so it is really small. IF you have the same signature for multiple child controls, you could pass a parameter to tell the page method which one to call/use.
EDIT: Per request (very very simple example). You can find other examples with more complex types being passed to the server side method. for instance see my answer here: Jquery .ajax async postback on C# UserControl
Example:
Page method: note the "static" part.
[WebMethod]
public static string GetServerTimeString()
{
return MyNamespace.UserControls.Menu.ucHelloWorld();
}
User Control Method:
public static string ucHelloWorld()
{
return "howdy from myUserControl.cs at: " + DateTime.Now.ToString();
}
Client ajax via jquery:
$(document).ready(function()
{
/***************************************/
function testLoadTime(jdata)
{
$("#timeResult").text(jdata);
};
$("#testTimeServerButton").click(function()
{
//alert("beep");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "MyPage.aspx/GetServerTimeString",
success: function(msg)
{
testLoadTime(msg);
}
});
});
});
Note: the dataFilter: function(data)... part of the ajax is so that it works with 2.0 and 3.5 asp.net ajax without changing the client code.
You can't...WebMethods have to be in WebServices or Pages, they cannot be inside UserControls.
Think about it a different way to see the issue a bit clearer...what's the URL to a UserControl? Since there's no way to access them you can't get at the method directly. You could try another way perhaps, maybe a proxy method in your page?

Using PageMethods with jQuery

Simply put I want to call public static methods decorated with WebMethod attribute inside my code-behind C# file from jquery.ajax to get some json and other simple stuff (in different functions). But instead I'm getting whole page :'(
I'm not using asp.net AJAX though I'm developing for .NET 3.5 framework and using VS 2008. (There are some restrictions from client)
Please let me know if I can use page-methods with using asp.net ajax or If not what is other simple solution?
After much deliberations I found the problem. I was using jquery's editable plugin. This was source of the problem. When jeditable calls jquery's ajax it sets ajax options like this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
success: function(result, status) {
if (ajaxoptions.dataType == 'html') {
$(self).html(result);
}
self.editing = false;
callback.apply(self, [result, settings]);
if (!$.trim($(self).html())) {
$(self).html(settings.placeholder);
}
},
error: function(xhr, status, error) {
onerror.apply(form, [settings, self, xhr]);
}
};
so it was sending the things as simple html and to use this with page methods we need to setup the things so that it sends as json. So we need to add something to the settings like this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
dataType: 'json', //Data Type
contentType: 'application/json; charset=utf-8', //Content Type
//....other settings
};
So I put two new properties in settings dataType and contentType and changed above to this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
dataType: settings.dataType,
contentType: settings.contentType,
//....other settings
};
Now another problem arised :( it was sending data (from submitdata property) as normal query-string which asp.net does not accept with json requests. So I had to use jquery's json plugin and change the way data is sent in ajax using following test on dataType:
if (settings.dataType == "json") {
if ($.toJSON) {
submitdata = $.toJSON(submitdata);
}
}
and it works like breeze!!!
Russ Cam posted this link in response to another question (so if this helps, go up vote his answer ;)):
Using jQuery to directly call ASP.NET AJAX Page Methods
Dave Ward has a series of posts that use jQuery directly with ASP.Net PageMethods, no MS Ajax UpdatePanel required. In particular this post will get you started.
I am not sure but i think WebMethods are accessible only through asp.net AJAX. I may be wrong though, because we dont use it that way at all. We do it in a slightly different way.
We have built a aspx page which accepts all our AJAX requests and passes them to the subsequent methods.
Server side code
If Not (Request("method") Is Nothing) Then
method = Request("method")
username = HttpContext.Current.User.Identity.Name.ToString
Select Case UCase(method)
Case "GETPROJECTS"
Response.ContentType = "text/json"
Response.Write(GetProjects(Request("cid"), Request("status")))
Exit Select
end select
end if
Client Side code [using jquery]
$.ajaxSetup({
error: function(xhr, msg) { alert(xhr, msg) },
type: "POST",
url: "Ajax.aspx",
beforeSend: function() { showLoader(el); },
data: { method: 'GetProjects', cid: "2", status:"open"},
success: function(msg) {
var data = JSON.parse(msg);
alert(data.Message);
},
complete: function() { hideLoader(el); }
});
Hope this helps.

Categories

Resources