javascript confirm message box in usercontrol - c#

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

Related

Alertify in a asp.net c# page

sorry if my english is poor.
I've a question, i think that the problem is my poor knowledge of javascript but.. i know that you can help me about this.
i've a page with an imagebutton, i use this for delete data and i need a confirmation dialog box. Alertify is pretty, i use altertify alert in server side like this:
string myScript2 = "alertify.error('message.')";
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(),
Guid.NewGuid().ToString(), myScript2, true);
return;
and work fine!
but i don't understand how to use alertify.confirm.
for example i've used
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../../js/alertify.min.js"></script>
<!-- include the core styles -->
<link rel="stylesheet" href="../../js/alertify.core.css" />
<!-- include a theme, can be included into the core instead of 2 separate files -->
<link rel="stylesheet" href="../../js/alertify.default.css" />
<script type="text/javascript">
$("#btElimina").on('click', function () {
alertify.confirm("This is a confirm dialog", function (e) {
if (e) {
alertify.success("You've clicked OK");
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
</script>
but nothing to do...i can't use onclientclick because alertify is a non-blocking instead a modal windows...
can you help me to understand? not to write code for me, but, to understand and make me viable
thank you
Henry
Replace alertify.success("You've clicked OK"); with return true;
and alertify.error("You've clicked Cancel"); with return false;
Also change this:
$("#btElimina").on('click', function () {
to this:
$("#<%=btElimina.ClientID%>").on('click', return function () {
I used this and it is working:
My button is :
<asp:ImageButton ToolTip="Çıkış" ID="ImageButton1" ImageUrl="Image/Exit.png" runat="server" OnClick="btnLogout_Click" />
My script is:
<script type="text/javascript">
$("#ImageButton1").on('click', function () {
alertify.confirm("This is a confirm dialog", function (e) {
if (e) {
alertify.success("You've clicked OK");
__doPostBack("<%=ImageButton1.UniqueID%>", "");
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
</script>
Here when i clicked "cancel" button returns false and doing nothing but when you clicked ok button i am doing postback for related button and you can write your own code in server side
protected void btnLogout_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Response.Redirect("~/Login.aspx");
...
}
I can't comment on the last comment below as I don't have 50 reputation, so I'm posting an answer simply to elaborate on Ratna's answer.
As per Ratna's answer, you should use server tags to refer to ASP.Net controls (controls with runat="server") to ensure that you get the control regardless of what ASP.Net renames the control to.
So to reiterate Ratna's answer:
Instead of
$('#btElimina').on(..
use
$('#<%= btElimina.ClientID %>').on(..
to make sure that you get the correct clientside control id in your jQuery script.

Can't get Javascript to fire from c# codebehind

I have read many posts here and many other sites and so I've gathered a few versions of HOW to do this. My problem is that I can't get it to do anything.
Here's the Javascript, just an alert for testing:
<script type="text/javascript">
function ICDcheck() {
alert('Patient has an ineligible diagnosis code!');
}
</script>
I tested this manually by adding the function to an OnClientClick of a button and it worked fine.
Here is what I've tried in the codebehind:
ClientScript.RegisterClientScriptBlock(this.GetType(), "uniqueKey", "ICDcheck()", true);
and...
string jsMethodName = "ICDcheck()";
ScriptManager.RegisterClientScriptBlock(this, typeof(string), "uniqueKey", jsMethodName, true);
and...
lblJavaScript.Text = "<script type='text/javascript'>ICDcheck();</script>";
This last one references a label I have sitting at the top of my asp : Content just below a script and the asp : ScriptManager block.
I've placed these bits in the button_click, the page_load, the sqldatasource_selecting, the formview_PageIndexChanging and always the same, nothing.
As always, thanks for your patience and help. My ignorance will likely be exposed as the problem, but I'm learning.
Try using Page.ClientScript :
Page.ClientScript.RegisterStartupScript( GetType(), "MyKey", "ICDcheck();", true);
Also install firebug and check if there are any script errors.
Try this. On your page, have a button:
<asp:Button ID="RunJsButton" runat="server" Text="Button" />
Then, in the code-behind, inject the script into the response and add the wireup to the button:
protected void Page_Load(object sender, EventArgs e)
{
string scriptToRun = #"function ICDcheck() { alert('Patient has an ineligible diagnosis code!');}";
ClientScript.RegisterClientScriptBlock(this.GetType(), "", scriptToRun, true);
RunJsButton.OnClientClick = "return ICDcheck();";
}
If that is the kind of thing you are after, you can refactor it a bit to implement best practice.
Try
<button ID="your_btn" onclick="javascript:your_function(); return false;"><asp:literal ID="your_literal" runat="server" /></button>
and
<script type="text/javascript">
function your_function() {
alert('Patient has an ineligible diagnosis code!');
}
</script>
This should work.
string jsToRun = "<script language=javascript>ICDcheck();</script>";
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Key", jsToRun);

Including Google Analytic tracking code dynamically at bottom of page after </Form> tag

I have a web application in which I want to track two different views of the same page from google analytic.
From code behind I am managing the two different views..but didn't find the way to manage the below script from code behind.
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("XX-XXXXXX-XX");
pageTracker._setDomainName(".DOMAIN.com");
pageTracker._trackPageview();
} catch (err) { }
</script>
So how can I change this script dynamically from code behind...?
A hack will be to place two hidden fields in the aspx part
<asp:HiddenField ID="TrackerCode" runat="server" ClientIDMode="Static">
</asp:HiddenField>
<asp:HiddenField ID="DomainName" runat="server" ClientIDMode="Static">
</asp:HiddenField>
Then at page load assign them
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TrackerCode.Text = "XX-XXXXXX-XX";
DomainName.Text = ".DOMAIN.com";
}
}
And finally place your script at the bottom of the page. ( After the labels we created )
<script type="text/javascript">
try {
var tcode = document.getElementById("TrackerCode").value;
var domain = document.getElementById("DomainName").value;
var pageTracker = _gat._getTracker( tcode );
pageTracker._setDomainName( domain );
pageTracker._trackPageview();
} catch (err) { }
</script>
Declare one function and define all your logic inside this function.
And call that function when the DOM is ready or on window.onload.
window.onload=function(){
//your function called it here or right your code here
}
Hope it will work

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 :(

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

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.

Categories