load user control dynamically with ajax AND have jquery document ready functionality - c#

I have a user control that will load via
public static string RenderControl(Control control)
{
var controlWriter = new StringWriter();
var htmlWriter = new Html32TextWriter(tw);
control.RenderControl(writer);
htmlWriter.Close();
return controlWriter.ToString();
}
AJAX used to write the html
$('#testDiv').html(result.d);
This is called through an ajax Post. It loads the user control fine, but since the javascript document load has already fired I cannot use jquery's document.Ready.
My situation is I need to load a user control dynamically and have jquery document.ready fire , or some equivalent. I would rather not use an updatepanel but if that is the only means of getting this done then that is what I will use.
What is an elegant solution to my problem?

You can use the built-in jQuery ajaxStop event to fire when an ajax call completes.
http://api.jquery.com/ajaxStop/

I solved something similar with a custom event that fires after the ajax contents were loaded and displayed.
Trigger the event inside the ajax function, after load and display:
$(document).trigger('ajaxLoadCallback');
And catch it in your document.ready script:
$(document).on('ajaxLoadCallback', function() {
// Your ready functions
}
If you create a function for everything that should be executed after document.ready than you can call this function (e.g. readyFunctions()) on document.ready and after the firing custom event.

public partial class Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
$(function(){
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
});

Related

How to get access drop-down control from static web method

I am trying to get access a drop-down that is in aspx page from static web method but it seems i can't get access and not what am i doing wrong. I want to set the dropdown index value to -1. thanks
this is what i am trying to do:
[System.Web.Services.WebMethod]
public static void Cancel()
{
myDDL.SelectedIndex = -1;
}
here is the javascript call
<script type="text/javascript" language="javascript">
function Func() {
//alert("hello!")
var result = confirm('WARNING');
if (result) {
//click ok button
PageMethods.Delete();
}
else {
//click cancel button
PageMethods.Cancel();
}
}
</script>
I am trying to get access a drop-down that is in aspx page from static web method
the web method in asp.net page are static, this mean are executed without page context(not completely true, you can access to Session), so what you need its retrieve result from web method, then make your update client side, something like(not tested, sorry):
jQuery.ajax({
url: 'callAJAX.aspx/Cancel',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var result = data.d.result;
$('#yourDropDownID')[0].selectedIndex = result;
}
});
It should be myDDL.selectedIndex = -1;
You cannot access a control inside webmethod..At the web service method level you cannot see anything about the page structure..
You can try this code for clearing dropdown..
Instead of calling pagemethod Cancel you can clear it inside javascript function itself..
var ddl = document.getElementById('myDDL');
ddl.options[ddl.selectedIndex] = 0;
Refer this link for extra reading..

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

consuming c# events in web forms NO ASP CONTROLS

How would I raise an event if my html syntax is the following:
<select runat="server" id="selection" onclick="inputCheck" />
I tried this in the code behind:
protected void inputCheck(object sender, EventArgs e)
{
//doesnt matter because it raised an on click.
}
Exception:Microsoft JScript runtime error: 'inputCheck' is undefined
Here is an example with jQuery posting back to the server using ajax method, very clean and easy to use. Let me know if you have questions.
--HTML page
<select id="selection" name="selection" />
--Place this following code in the head tag in the html surrounded by the script tags; you must also include the latest jquery code (free download from http://www.jquery.com)
$(document).ready(function()
{
$("#selection").click(function()
{
var selectionValue = $(this).val();
$.ajax({
type: "POST",
url: "CodeBehindPage.aspx/WebMethodName",
data: "{'input':'" + selectionValue + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//return value goes here if any
}
});
}
});
//Code behind page
[System.Web.Services.WebMethod]
public static bool WebMethodName(string input)
{
try
{
//do something here with the input
return (true);
}
catch(Exception ex)
{
throw ex;
}
}
--This will post the code to the server without any postbacks, which I like. In order to test, set a break point inside of the WebMethodName function and view the input passed in. HTH
The onclick in your first snippet runs only in javascript. To raise the event server-side, the first step is to build a javascript method for this event. From there, you have a few options:
You can build an ajax request to call a WebMethod
You can post the event back to the original page. Since you aren't using asp control, you will have to have code in your page_load to check the posted data for the event and raise it on your own.

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?

Categories

Resources