consuming c# events in web forms NO ASP CONTROLS - c#

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.

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

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

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

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.

Categories

Resources