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

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

Related

Update markup dynamically after JS Ajax call to CodeBehind static function

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');
}
});

JQuery code to call a c# method not working

I am calling a C# function from JQuery but it is giving error.
The JQuery function is written in ascx file and C# function to be called is written in that page's code behind. I am loading the user control into an AJAX tab on tab change event.
Googling, I got that I can not call C# function written in user control. So I written a function in host page(ASPX) and this function is calling my user control function.
But the AJAX request is some how failing, I don't know where. But interesting thing is I have kept a debugger in the error function and I checked the error object.
Status is 200, Status is OK, readyState is 4
and ResponseText is the markup of the page. This means the page is served but the kept the break point in the C# function. It never hits.
I have no idea what's happening. Also this is the first time I am calling a C# function from front end. I don't have detailed idea of what happens under the hood. Please help. Below is the code:
JQuery
$(function () {
$(".hint ul li").click(function () {
// remove classes from all
$(".hint ul li").removeClass("active");
// add class to the one we clicked
$(this).addClass("active");
//Ankit J, Implement logic to call jquery
var Availability = this.childNodes[0].innerText.trim();
debugger;
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/CallUCMethodFromJQuery",
data: "{'sAvailability' : 'Availability'}",
dataType: "json",
success: fnsuccesscallback,
error: fnerrorcallback
});
});
});
function fnsuccesscallback(data) {
alert("success-->" + data.d);
}
function fnerrorcallback(result) {
debugger;
alert("error-->"+result);
}
ASPX page's code behind function
[System.Web.Services.WebMethod]
public void CallUCMethodFromJQuery(string sAvailability)
{
MyNamespace.UserControls.ControlName m = new UserControls.ControlName();
m.EditAvailabilityValue(sAvailability);
}
And then the UserControl's code behind
public void EditAvailabilityValue(string sAvailability)
{
}
Sorry for not mentioning.... JQuery is in the User Control because the source of click event is a li element which is in the User Control. Also the UserControl is in a folder UserControls and the host page is in the Pages folder and both these folders are in root folder.
Add contentType: "application/json; charset=utf-8" attribute to your ajax call:
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/CallUCMethodFromJQuery",
data: "{'sAvailability' : 'Availability'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: fnsuccesscallback,
error: fnerrorcallback
});
then change EditAvailabilityValue method in the user control to static:
public static void EditAvailabilityValue(string sAvailability)
{
}
and change CallUCMethodFromJQuery method in the aspx page code behind to static so it can be called using jQuery:
[System.Web.Services.WebMethod]
public static void CallUCMethodFromJQuery(string sAvailability)
{
MyNamespace.UserControls.ControlName.EditAvailabilityValue(sAvailability);
}

How can I clear asp.net session value in OnUnload event in javascript

I'd like to clear ASP.NET session value when browser closed. I've onunload function defined in my html page, but I don't know how can I clear session value in this Javascript method ?
<body onunload="myUnloadFunction()">
<script>
function myUnloadFunction()
{
// Needs asp.net session code here
}
</script>
Please let me know Is it possible else any other preferable way of doing.
Try this:
Code-behind:
[WebMethod]
public static void ClearYourSessionValue()
{
// This will leave the key in the Session cache, but clear the value
Session["YourKey"] = null;
// This will remove both the key and value from the Session cache
Session.Remove("YourKey");
}
JavaScript:
$.ajax({
type: "POST",
url: "PageName.aspx/ClearYourSessionValue",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
If you want more information about ASP.NET AJAX Page Methods and how to invoke them via AJAX then read Using jQuery to directly call ASP.NET AJAX page methods

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?

jQuery Ajax passing the Form Collection

I was wondering if it is possible to pass the forms collection from within an ajax method in jQuery?
$.ajax({
type: "POST",
url: "/page/Extension/" + $("#Id").val(),
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#result").html(msg);
false;
}
});
If it is possible to pass in the forms collection then when it arrives at the method within c# how to you read it in?
You can do something like this:
var form = $("#myForm").serialize();
$.post("/Home/MyUrl", form, function(returnHtml)
{
//callback
});
Then on the C# side you should be able to do something like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyUrl(FormCollection collection)
{
//do what you gotta do
}
I think this should work.
EDIT: I just noticed that I simply assumed you were referring to ASP.NET MVC. If not, let me know as this answer is specific to MVC.
You can use the Ajax.BeginForm method from ASP.NET MVC. It will use Microsoft's ajax to do the request, but you can have a JQuery method execute upon completion. Or you can use an UpdatePanel and register a javascript to run with the ScriptManager once the UpdatePanel loads. Another thing you could try is using a jquery like the following: $(':input') to get a collection of all input, textarea, select and button elements(JQuery documentation), and pass that as the data into your request.
Got this working all okay, and it returns the input form collection in the FormCollection
input = $(':input')
$.ajax({
type: "POST",
url: "/page/Extension/" + $("#Id").val(),
data: input,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#result").html(msg);
false;
}
});

Categories

Resources