C# AJAX Web methods - What am I doing wrong? - c#

This maybe a very noobish question but I am trying to implement a simple web method using AJAX C# and asp.net here is the code:
C# code behind:
using System.Web.Services;
public partial class Controls_LeftNavigation : System.Web.UI.UserControl
{
[WebMethod]
public static string MyMethod()
{
return "Hello";
}
}
Asp.net page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<script type="text/javascript">
function pageLoad() {
var acc = $find('<%= Accordion1.ClientID %>_AccordionExtender');
acc.add_selectedIndexChanging(ClickHandler);
}
function ClickHandler() {
// Do whatever you want.
alert('Something is happening!');
alert(PageMethods.MyMethod());
}
</script>
when the navigation button is clicked it displays the "Something is happening!" message box but does not show the page method alert.
I am using the ASP AJAX toolkit accordion which is why the page load event adds the click handler event to that control.

PageMethods on user controls are not supported.

The page method is asynchronous, you must provide an onSuccess handler like so:
function OnSuccess(result) {
alert(result);
}
function ClickHandler() {
PageMethods.MyMethod(OnSuccess);
}
You will also need to prevent the SelectedIndexChanging event from doing a Post Back or else the page will not be able to handle the returning result.

Related

javascript confirm message box in usercontrol

I have a usercontrol in which i have placed a javascript function which shows the confirm message box. That usercontrol is further called on aspx page.
the function i wrote is :
<script> function CreatePopup() {
return confirm("Do you confirm?");
}
</script>
and then i called the function on the button :
<asp:Button ID="btnAuthenticate" runat="server" Text="Authenticate"
OnClientClick="return CreatePopup();"
OnClick="btnAuthenticate_Click" />
What happens is this code is not working.. is there any problem with my function here or do we have certain limitations to look after when adding any scripts in usercontrol?
This is blowing me off as this was supposed to be the most simpliest task i thought to be!!!
I Use Javascript with a page method
<script>
function Delete(id) {
if (confirm("Delete Record?"))
{
PageMethods.DeleteSomething(id, onsuccessDel, onfailDel);
}
}
function onsuccessDel(msg) { window.alert('Did IT!'); }
function onfailDel(err) {window.alert('Some Error Occured!'); }
</script>
And then the HTML or ASPX should have :
<asp:ScriptManager ID="scriptMgr" runat="server" ViewStateMode="Disabled" EnablePageMethods="true" />
Delete
The Server side code :
[WebMethod]
public static void DeleteSomething(int id)
{
try{
//some code c#
}
catch (Exception ex)
{
throw new Exception(ex.toString());
}
}
You can see the working demo there: Demo.
And the code from here: code.
Hope this will be helpful to you.
The following worked for me to display a alert box from user control (ascx).
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('I am from the Server');", true);

calling a button click event

Is it possible to call "button click event" in one web form ,from a button in another web form?
what actually i'm trying to do is, i've a link button in second form, when it is clicked, i want the first form to disply and also button in first form to be clicked.
can anyone help me do this?
I assume you are using jQuery and have basic knowledge of it. So do it this way:
<form id="form1" style="display:none">
<Asp:Button id="button1" onclick="alert('clicked')" >button1</Asp:Button>
</form>
<form id="form2">
<Asp:LinkButton url="javascript:void(0);" onclick="call1();">Link button1</Asp:LinkButton>
</form>
<script>
function call1()
{
$("#form1").show();
$("#button1").trigger("click");
}
</script>
Note: The asp markup written by me can give compilation errors, so please resolve those yourself. I put that just to give you the basic idea of how it is handled.
create a Delegate in WebForms (I have used in WinForms)
public delegate void LoginDelegate(string s);
loginAirLineDelegate = new LoginDelegate(DisableToolStripMenuItems);
public void DisableToolStripMenuItems(string s)
{
this.viewToolStripMenuItem.Visible = true;
this.bookingToolStripMenuItem.Visible = true;
this.existingUserToolStripMenuItem.Visible = false;
this.newUserToolStripMenuItem.Visible = false;
this.toolStripStatusUserID.Text = "USerID :- "+s;
this.LoginUserId = s;
}
I have passed the Delaqgte to other Form with Construtor as argumnet.
I can able to fire the delegate from the second form like this
logDelegate(textBoxUserName.Text);

jquery function doesn't work when called from usercontrol

I have an aspx page which holds 2 user controls
UC1: Edit page - this has the fields for editing or data entry.
UC2: Notification page - this has a simple message box with jquery function
in my aspx i have this function:
public void ShowMessage(string status, string message)
{
Notification1.Message = message; //this is my user control UC2
Notification1.Status = status;
Notification1.DataBind();
}
now when my aspx page needs to show a message this works fine, but when i want the user control 1 to show a message like (invalid field, or wrong amount) it doesn't do anything. Now it gets called but jquery just doesn't react to it.
in UC2 -notification user control this is what I have:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
<script type="text/javascript">
function showMsg(classname) {
$("#MsgBox").attr('class', classname);
$("#MsgBox").show().delay(5000).fadeOut();
}
</script>
<div id="MsgBox" class="info"><asp:Label ID="lblMessage" runat="server" /></div>
codebehind
public string Status{ get; set; }
public string Message { get; set; }
public override void DataBind()
{
if (Message != string.Empty)
{
lblMessage.Text = Message;
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "showMsg('" + Status + "');", true);
}
}
and this is how i call the function from user control to aspx page:
((myaspxpage)this.Page).ShowMessage("error", "This is my error message.");
any help will be much appreciated! and if further details is needed just let me know.. Thanks in advance.
**EDIT: I tried putting the jquery and message box inside my Edit page to see if it would work that way and it doesn't So it seems that jquery is not working well within a usercontrol??
Move your codes of DataBind() method into OnPreRender. This should work. The reason is that you don't know which code from which step of your page cycle (init, load, bind, ...) is going to change the Message property.
Like in your case it seems you have a button click event where you are setting the Message property from. This is too late because your Notification1 control is already databound.
Leaving it as the latest stage makes it work:
protected override void OnPreRender()
{
if (Message != string.Empty)
{
lblMessage.Text = Message;
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "showMsg('" + Status + "');", true);
}
}
I found the error is what that my button that was calling the function in aspx page was inside an update panel and i needed to add a trigger event to make it work.. Thanks everybody for the help it was that update panel causing the error :(

Fetch JS return value in server side page_load event in asp.net

I have an aspx master/content page scenario. The parent page has an IFrame which points to a child.aspx. The child.aspx has a checkbox, On page_load of child.aspx, I want to show/hide the checkbox depending on the following logic:
- if the child.aspx is opened directly, then I have to show the checkbox.
- if the child.aspx is opened in the IFrame, then I have to hide the checkbox.
Basically, I want to check in child.aspx, if it contains a parent window then hide the checkbox control otherwise show it.
I will prefer the show/hide code in codebehind in Page_load event as I have to execute some more logic depending on whether the it is opened from parent window or not.
Till now I did the following:
In child.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
<script language="javascript" type="text/javascript">
function DoesParentExists()
{
var bool = (parent.location == window.location)? false : true;
var HClientID ='<%=hfDoesParentExist.ClientID%>';
document.getElementById(HClientID).Value = bool;
}
</script>
<div>
<h2>Content - In IFrame</h2>
<asp:HiddenField runat="server" id="hfDoesParentExist" />
<asp:CheckBox ID="chkValid" runat="server" />
<asp:ImageButton ID="ImageButton_FillW8Online" ImageUrl="~/images/expand.gif"
OnClick="btnVerify_Click" runat="server" style="height: 11px" />
</div>
</asp:Content>
in client.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DoesParentExists", "DoesParentExists()", true);
if (hfDoesParentExist.Value == "true")
{
chkValid.Visible = false;
}
}
Using RegisterClientScriptBlock, I get error in JS. That the object hfDoesParentExist doesn't exist 'coz the control is not yet created. Right? I tried using RegisterStartupScript but in codebehind I always get null in hidden variable. I don't want to use the on button click or something like it. I need it on page_load event only. How to resolve the issue?
This line:
document.getElementById(HClientID).Value = bool;
Should be: (lower case value)
document.getElementById(HClientID).value = bool;
Also you cannot check the value of a hidden field set by javascript register callback, in the current executing context on the server side.
I would move the logic to the client side to hide or show the checkbox. If the field must indeed be removed from the page you can do that as well with javascript.
function DoesParentExists()
{
var bool = (parent.location == window.location)? false : true;
var cehckboxId ='<%=chkValid.ClientID%>';
if(bool){
document.getElementById(cehckboxId).style.display = 'none';
}
else {
document.getElementById(cehckboxId).style.display = 'block';
}
}
You may want to wrap the checkbox with a div and hide the container also to include the label.
To do it server-side, I would rely on a querystring parameter. Have the parent page load the child page by appending ?inframe=1. Then check for that value in your Page_Load.

How to detect a postback in frontend (aspx)

I need to detect a postback in the frontend so I can use it with JQuery to change a class on page load. How can I do this?
You can check the IsPostBack property. Eg:
<script type="text/javascript">
$(function()
{
var isPostBack = <%=Page.IsPostBack.ToString().ToLower()%>;
if (isPostBack)
{
alert("Postback");
}
});
</script>
Stolen from this post:
On the server side have this
if(IsPostBack)
{
// NOTE: the following uses an overload of RegisterClientScriptBlock()
// that will surround our string with the needed script tags
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}
On client side this
if(isPostBack) {
// do your thing
}
I put this variable inside the header tag of my asp.net web forms page.
<script type="text/javascript">
var isPostBack = ("true"==="<%= Page.IsPostBack ? "true" : "false" %>");
</script>
The var contains a Boolean. The comparison can probably be shortened.
Simple:
if you're using jquery it has to go after(jquery goes nuts otherwise):
$(document).ready(function(){
});
var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
Then
function whatever(){
if (isPostBack){
//Whatever you want to do
}else{
//Whatever else you want to do
}
}
I'm actually using it with jquery to show a web service status box then force a postback to refresh a ListView, so when it posts back it doesn't invoke the web service or show the status box just the updated ListView data.
$("a[href^='javascript:__doPostBack']").click(function () {
// do something
});

Categories