I Have a common method that displays alert message using page.clientScript. But later on i added update panel. Now this piece of code is not working. So I need to call there scriptmanager, but i get some error message that it is accessible there.
Below is my ShowMessage method of common.cs file
private static void ShowMessage(Page currentPage, string message)
{
var sb = new StringBuilder();
sb.Append("alert('");
sb.Append(message);
sb.Append("');");
currentPage.ClientScript.RegisterClientScriptBlock(typeof(Common), "showalert", sb.ToString(), true);
}
So how do I use this method under update panel
Make use of : ScriptManager.RegisterClientScriptBlock Method
ScriptManager.RegisterClientScriptBlock(
this,
typeof(Page),
"TScript",
script,
true);
const string scriptString = "<script type='text/javascript'> alert('message');</script>";
ClientScriptManager script = Page.ClientScript;
script.RegisterClientScriptBlock(GetType(), "randomName", scriptString);
For use in a class file:
public static void SendAlert(string sMessage)
{
sMessage = "alert('" + sMessage.Replace("'", #"\'").Replace("\n", #"\n") + "');";
if (HttpContext.Current.CurrentHandler is Page)
{
Page p = (Page)HttpContext.Current.CurrentHandler;
if (ScriptManager.GetCurrent(p) != null)
{
ScriptManager.RegisterStartupScript(p, typeof(Page), "Message", sMessage, true);
}
else
{
p.ClientScript.RegisterStartupScript(typeof(Page), "Message", sMessage, true);
}
}
}
This could be expanded to include other possible handlers, but for the moment this is how I solved the problem.
Try this in .cs file
var page = HttpContext.Current.CurrentHandler as Page;
ScriptManager.RegisterStartupScript(page, page.GetType(), "alert", "alert('Success');window.location ='Home.aspx';", true);
It's working for me ^^
Here's how I did it:
public partial class JQuery
{
private Page page;
public JQuery(Page pagina) {
page = pagina;
}
public void Alert(string Title, string Message)
{
Message = Message.Replace("\n", "<br>");
string command = String.Format("myCustomDialog('{0}','{1}')", Title, Message);
ScriptManager.RegisterClientScriptBlock(page, this.GetType(), "", command, true);
}
}
Then you can use like this:
JQuery jquery = new JQuery(this.Page);
jQuery.Alert("Title", "Look, a jQuery dialog!");
Related
I am currently developing a DotNetNuke module. However, I failed to prompt user an alert dialog box in certain situations like record duplication.
I am using the following code to display an alert box in Controller class.
EditForm edForm = new EditForm();
ScriptManager.RegisterClientScriptBlock(edForm, edForm.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
The following is my full code.
Form.ascx.cs
void cmdUpdate_Click(object sender, EventArgs e)
{
UdtController.UpdateRow(Data, ModuleId, False);
}
UdtController.cs
public void UpdateRow(DataSet ds, int rowNr, bool isDataToImport)
{
var values = new Dictionary<int, string>();
string strIsUnique = "";
foreach (DataRow field in ds.Tables[DataSetTableName.Fields].Rows)
{
var strColumnName = field[FieldsTableColumn.Title].ToString();
strIsUnique = field[FieldsTableColumn.Searchable].ToString();
var strValueColumn = ((!isDataToImport &&
ds.Tables[DataSetTableName.Data].Columns.Contains(strColumnName +
DataTableColumn.
Appendix_Original))
? strColumnName + DataTableColumn.Appendix_Original
: strColumnName);
if (strIsUnique == "True")
{
int uniqueDataCount = FieldController.uniqueData(currentRow[strValueColumn].AsString());
if (uniqueDataCount == 0)
{
if (ds.Tables[DataSetTableName.Data].Columns.Contains(strValueColumn))
{
values.Add(field[FieldsTableColumn.Id].AsInt(), currentRow[strValueColumn].AsString());
}
}
else
{
EditForm edForm = new EditForm();
ScriptManager.RegisterClientScriptBlock(edForm, edForm.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
break;
}
}
else
{
if (ds.Tables[DataSetTableName.Data].Columns.Contains(strValueColumn))
{
values.Add(field[FieldsTableColumn.Id].AsInt(), currentRow[strValueColumn].AsString());
}
}
}
FieldController.UpdateData(userDefinedRowId, values);
}
You need to reference the Page, not create a new form.
Page page = HttpContext.Current.CurrentHandler as Page;
ScriptManager.RegisterStartupScript(page, page.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
However DNN has it's own message box you could use:
http://uxguide.dotnetnuke.com/UIPatterns/AlertDialog.html
here is my code
ASPX Code:
<asp:Button ID="Button4" runat="server" onclick="Button4_Click" Text="Insert" />
C#:
public void MsgBox(String MessageToDisplay)
{
Label lblForMsg = new Label();
lblForMsg.Text = "<script language='javascript'>window.alert('" + MessageToDisplay + "')</script>";
Page.Controls.Add(lblForMsg);
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlCommand com = new SqlCommand("insert into employe values(#id,#pass)", con);
SqlParameter obj1 = new SqlParameter("#Id", DbType.StringFixedLength);
obj1.Value = TextBox4.Text;
com.Parameters.Add(obj1);
SqlParameter obj2 = new SqlParameter("#pass", DbType.StringFixedLength);
obj2.Value = TextBox5.Text;
com.Parameters.Add(obj2);
com.ExecuteNonQuery();
con.Close();
MsgBox("Account Created");
if (Session["regis"] == null)
{
Response.Redirect("Profile.aspx");
}
else
{
Response.Redirect("Login.aspx");
}
}
i want that when i click on button4, msgbox show, after that when i click ok on msgbox then it check the condition and response to the page.
i am using visual studio 2010,asp.net/c#
To display a javascript alert message you should use RegisterClientScriptBlock
public static void ShowMessageAndRedirect(string message, string lpRedirectPage)
{
string cleanMessage = MessageToDisplay.Replace("'", "\'");
Page page = HttpContext.Current.CurrentHandler as Page;
string script = string.Format("alert('{0}');", cleanMessage);
script += " window.location.href='" + lpRedirectPage+ "';"
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", script, true /* addScriptTags */);
}
}
Similar question here: JavaScript: Alert.Show(message) From ASP.NET Code-behind
if (Session["regis"] == null)
{
ShowMessageAndRedirect("Account Created","Profile.aspx");
}
else
{
ShowMessageAndRedirect("Account Created","Login.aspx");
}
I think if you want to display "Account Created to the User then do the following =
Response.Write("window.alert('" + MessageToDisplay + "');");
In your server-side code, you're attempting to add the message box, but immediately after that, either way your method ends with a Response.Redirect - so you're sending the user off to a new page (even if one of those pages is the same URL as the page you came from).
If you want the message box to show if the process was successful (your "account created" scenario), then whichever page you redirect to needs to include that javascript message box when it renders.
Since you like to use MsgBox.show() like that of windows form. This class will help you (vb.net)
Imports Microsoft.VisualBasic
Public Class MsgBox
Public Shared Sub Show(ByRef page As Page, ByVal strMsg As String)
Try
Dim lbl As New Label
lbl.Text = "<script language='javascript'>" & Environment.NewLine _
& "window.alert(" & "'" & strMsg & "'" & ")</script>"
page.Controls.Add(lbl)
Catch ex As Exception
End Try
End Sub
End Class
From within aspx.page, it can be called like this
Msgbox.show(Me,"Alert something")
My code is as follows:
void CallToast(String msg, String cls)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>");
sb.Append("toast(" + msg + "," + cls + ");");
sb.Append("</script>");
ScriptManager.RegisterStartupScript(this, this.GetType(), "ajax", sb.ToString(), false);
}
protected void Button1_Click(object sender, EventArgs e)
{
CallToast("Oops... Some thing is wrong...", "toast-error");
}
AND JAVASRICPT FUNCTION IS :
<script type="text/javascript">
function toast(sMessage, sIco) {
if ($('.toast').length <= 0) {
var container = $(document.createElement("div"));
container.addClass("toast");
container.appendTo(document.body);
}
var message = $(document.createElement("div"));
message.addClass(sIco);
message.text(sMessage);
message.appendTo($('.toast'));
message.delay(100).fadeIn("slow", function () {
$(this).delay(5000).fadeOut("slow", function () {
$(this).remove();
});
});
}
What is the problem? notification is not seen on a button click. i hv written css file.
Your javascript function name is toast ?
Try this one ,
ScriptManager.RegisterStartupScript(this, this.GetType(), "toast()", sb.ToString(), false);
How can i redirect to another page and open a new window in one button click?
protected void ASPxButton_save_Click(object sender, EventArgs e)
{
try
{
//do other stuff
if (oSoins.DEVENIR_ECVAC_PAR != 0)
{
string AdrUrl = "Print_DosSoin.aspx?SoinId=" + Soin_Id;
ClientScript.RegisterStartupScript(this.GetType(), "newWindow", String.Format("<script>window.open('{0}');</script>", AdrUrl));
}
Response.Redirect("DossierSoin_Liste.aspx");
}
catch (ThreadAbortException) {/* do nothing, it might be a response.Redirect exception */}
catch (Exception excThrown)
{
lbl_err.Text = excThrown.Message;
if (excThrown.InnerException != null) lbl_err.Text += "-->" + excThrown.InnerException.Message;
string TempMsg = "DosSoin Fiche " + Appel_ID + "-- ASPxButton_save_Click -->" + lbl_err.Text;
Outils.SendingEmail(TempMsg);
}
With the script above it's redirecting but does not open a new window.
Thank you in advance.
You should modify your javascript to the following:
string script = default(string)
if (oSoins.DEVENIR_ECVAC_PAR != 0)
{
string AdrUrl = "Print_DosSoin.aspx?SoinId=" + Soin_Id;
script = string.Format("window.open('{0}'); ", AdrUrl);
}
script += " window.location.href = 'DossierSoin_Liste.aspx';";
ClientScript.RegisterStartupScript(this.GetType(), "newWindow", script, true);
This will create a new window then redirect on the client.
The situation is to open a fancy box on the page load,
Please find the below html, and the code behind I am using but with no success.
protected void Page_Load(object sender, EventArgs e)
{
if (SessionController.CurrentMember != null)
{
if (Request.IsAuthenticated)
{
int memberId = SessionController.CurrentMember.MemberID;
bool checkaccepted = CheckAcceptedTermsandConditions(memberId);
if (!checkaccepted)
{
string script = #"<script>$(document).ready(function() {
$(""#onlineCasinoTandC"").fancybox({
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : false,
'overlayOpacity': 0.5,
'width' : 800,
'showCloseButton': true,
});
$(""#onlineCasinoTandC"").click();
});</script>";
ClientScript.RegisterStartupScript(this.GetType(), "fancybox", script);
onlineCasinoTandC.HRef = "/Common/EN/TermsandConditions.aspx";
}
}
}
}
Regards
Srividhya
delete the extra comma at the end of this line
'showCloseButton': true
And if u want to trigger, Click event, it should be
$('#foo').trigger('click');
Please find the below solution.
on page load
string script = #"<script type=""text/javascript"">$(document).ready(function() {$(""#termsandConditions"").fancybox({'transitionIn':'elastic','transitionOut':'elastic','speedIn':600,'speedOut':200,'overlayShow':false,'overlayOpacity': 0.5,'width':800,'href':""/Contents/Common/EN/TermandConditions.aspx""}).trigger('click');});</script>";
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsStartupScriptRegistered(cstype, script))
{
cs.RegisterStartupScript(cstype, "fancybox", script);
}
Regards
Vidya