Hi I want to call a client side javascript confirm message from code behind in asp.net.
I want to use the true or false return value from the confirm message.
I'm doing like this, but this is not the correct way, please tell me how can I do the same.
ScriptManager.RegisterStartupScript(this, this.GetType(), "myconfirm", "confirm('No Rule Type Ids found for This Rule.');", true);
I think This is what you want to achieve:
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to save data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
.aspx code
<asp:Button ID="btnConfirm" runat="server" OnClick = "OnConfirm" Text = "Raise Confirm" OnClientClick = "Confirm()"/>
C#
public void OnConfirm(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
}
}
Instead of directly writing confirm in the code behind. Write the name of javascript function.
Forexample,
ScriptManager.RegisterStartupScript(this, this.GetType(), "myconfirm", "OpenConfirmDialog();", true);
In your javascript, write the function OpenConfirmDialog
<script>
function OpenConfirmDialog()
{
if (confirm('No Rule Type Ids found for This Rule.'))
{
//True .. do something
}
else
{
//False .. do something
}
}
</script>
You can't mix client-side code with server-side code. The client side code (javascript) will not be sent to the client (browser) until the server-side code has completed.
You will need to stop processing and show the question to the user (maybe by a redirect to some other page), and then (on confirm) continue with your processing.
Response.Write("<script language=javascript>");
Response.Write("if(confirm('El vehiculo no existe, Deseas crear el registro?')){window.location.href='IngresoVehiculos.aspx'}");
Response.Write("</script>");
use:
Response.Write("<script>alert('Open Message!');</script>");
You can do it without using Javascript function
Try
if (MessageBox.Show("confirm('No Rule Type Ids found for This Rule.')",
"myconfirm",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// yes
}
else
{
//No
}
Related
<%--Confirmation Box--%>
<script type="text/javascript" language="javascript">
function alertbox() {
if (confirm("Are you sure?") == true)
{
document.getElementById('<%= hdnYesNo.ClientID %>').value = "YES";
}
else
{
document.getElementById('<%= hdnYesNo.ClientID %>').value = "NO";
}
}
</script>
How to rewrite this code in C# as codebehind? I would like have a confirm box with yes or no buttons.
protected void Page_Load(object sender, System.EventArgs e)
{
string csName = "PopupScript";
Type csType = this.GetType();
ClientScriptManager csm = Page.ClientScript;
if (!csm.IsStartupScriptRegistered(csType, csName)) {
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("function alertbox() {");
sb.Append("if (confirm('Are you sure?') == true) ");
sb.Append("{");
sb.Append("document.getElementById('" + hdnYesNo.ClientID + "').value = 'YES';");
sb.Append("}");
sb.Append("else");
sb.Append("{");
sb.Append("document.getElementById('" + hdnYesNo.ClientID + "').value = 'NO';");
sb.Append("}");
sb.Append("</script>");
csm.RegisterStartupScript(csType, csName, sb.ToString());
}
}
you can use like this way
Page.ClientScript.RegisterStartupScript(this.GetType(), "Confi", "if(confirm('Are you sure?') == true){ document.getElementById('txtValue').value ='YES';}else{document.getElementById('txtValue').value ='NO';}", true);
You can use ClientScriptManager class and its methods, for example RegisterClientScriptBlock. Depends on when you want the javascript to execute.
See details here:
http://msdn.microsoft.com/en-us/library/System.Web.UI.ClientScriptManager_methods.aspx
You need javascript for this, it's not possible in code behind. Code behind is run on the server before the page is sent to the user, javascript is run on the user's computer.
If you want to get access to their answer in code behind (possible and straightforward), you can use ajax or you can postback.
If you want to have this popup to come up when you press on a .Net asp:button control, then you can put a javascript function in the "OnClientClick" attribute of the control.
EDIT: If you need help with any of the above, let us know and help will be provided :).
EDIT2: Due to the discussion below, I guess I should clarify: You can (obviously) construct javascript on the server side before passing it to the client, but the example you gave is NOT a case where you should be doing that (an example of where this might be a good idea would be a script that has variables read from a database or something similar that doesn't need to be dynamic between page loads).
another option is to create the script in the /View folder and user razor for generating the script.
then you could point to the page in the tag like
<script src="~/ScriptGenerator/MyScript" />
for pointing the controller ScriptGeneratorController that expose the action MyScript
i'm having issues with code that used to work, but now fails to run. I have a character counter on a textbox with the below code in the .aspx file:
<script>
var bName = navigator.appName;
function taLimit(taObj, maxL) {
if (taObj.value.length == maxL) return false;
return true;
}
function taCount(taObj, Cnt, maxL) {
objCnt = createObject(Cnt);
objVal = taObj.value;
if (objVal.length > maxL) objVal = objVal.substring(0, maxL);
if (objCnt) {
if (bName == "Netscape") {
objCnt.textContent = maxL - objVal.length;
}
else { objCnt.innerText = maxL - objVal.length; }
}
return true;
}
function createObject(objId) {
if (document.getElementById) return document.getElementById(objId);
else if (document.layers) return eval("document." + objId);
else if (document.all) return eval("document.all." + objId);
else return eval("document." + objId);
}
</script>
aspx:
<asp:TextBox ID="txtDescription" runat="server" Font-Names="Courier New"
TextMode="MultiLine" Width="398px" onKeyPress="return taLimit(this, 50)" onKeyUp="return taCount(this,'myCounter1', 50)"></asp:TextBox>
<br /><B><SPAN id='myCounter1'>50</SPAN></B>
This worked without problems before, but now i want a way to update the myCounter1 On page load, to show the correct remaining characters, i'm loading text from database into the textbox.
right now i'm using this:
ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript", "document.getElementById('myCounter1').textContent = 50 - " + txtDescription.Text.Length.ToString() + ";", true);
This works, it sets the character counter to the correct remaining characters. Now the issue is however, when text is typed in the textbox, the caracter counter won't update anymore dynamically. Could someone tell me why?
Using js. Put this inside your script:
<script type="text/javascript">
window.onload = function(){
taCount(document.getElementById('<%=txtDescription.ClientID%>'),'myCounter1', 50);
}
</script>
Remove the Server side scriptmanager code.
I have a button and onclick is set to this method which should display a simple JS alert pop up window:
string message = "File is already open. <br>Please close the file and try again.";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
I have used the code above before and it has worked but not this time.
The only difference is that I was using master pages for the other site and not for this one, and this one also has a timer going.
Is there anything JS related to load in the <head> of the aspx page?
protected void btnToCSV_Click(object sender, EventArgs e)
{
try
{
StreamWriter writer = new StreamWriter(#"\\server location\test.csv");
Some writer.write stuff...
writer.Close();
}
catch (Exception ex)
{
lblMessage.Visible = true;
string message = "File is already open. Please close the file and try again.";
ClientScript.RegisterClientScriptBlock(
this.GetType(),
"alert",
string.Format("alert('{0}');", message),
true);
}
}
Try with this simplyfied version
string message = "File is already open. <br>Please close the file and try again.";
ScriptManager.RegisterClientScriptBlock(
UpdatePanel1, // replace UpdatePanel1 by your UpdatePanel id
UpdatePanel1.GetType(), // replace UpdatePanel1 by your UpdatePanel id
"alert",
string.Format("alert('{0}');",message),
true );
You are not encoding anything here:
sb.Append(message);
If the message is Hello Jean d'Arc (notice the single quote) you will end up with the following code:
alert('Hello Jean d'Arc');
I am leaving you imagine the result of this => a javascript error of course.
To fix this error make sure that you have properly encoded the argument. One way to do this is to JSON serialize it:
var serializer = new JavaScriptSerializer();
sb.AppendFormat("alert({0});", serializer.Serialize(message));
Also since you have already includeed the <script> tags, make sure that you pass false as last argument of the RegisterClientScriptBlock function to avoid adding them twice:
ClientScript.RegisterClientScriptBlock(
this.GetType(),
"alert",
sb.ToString(),
false // <!---- HERE
);
And here's how the full code might look like:
var message = "File is already open. <br>Please close the file and try again.";
var sb = new StringBuilder();
sb.Append("<script type=\"text/javascript\">");
sb.Append("window.onload=function() {");
var serializer = new JavaScriptSerializer();
sb.AppendFormat("alert({0});", serializer.Serialize(message));
sb.Append("};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(
this.GetType(),
"alert",
sb.ToString(),
false
);
Another remark is that if you are doing this in an AJAX call you should use the ClientScript.RegisterStartupScript method.
I am tryong to do the following in a Row_Command event of a gridview. But the the pop up box never comes up, I have tried it in so many different ways.. but yet no luck. Please if someone can see the issue i would really appreciate a pointer.
protected void Gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "Merchant")
{
if (ItemsAvailable)
{
StringBuilder sb = new StringBuilder();
MyClass class = new MyClass();
TList<LineItems> otherItems = MyClass.GetItems(id);
bool IsNotAvailable = false;
foreach (LineItems item in otherItems)
{
Merchandise skuMerchandise = skuMerchandise.GetMerchandise(otherItems.mid);
if (skuMerchandise != null)
{
if (skuMerchandise.AvailableItems <= 0)
{
sb.Append(OtherItems.Name);
sb.Append(Environment.NewLine);
IsNotAvailable = true;
}
}
}
if (IsNotAvailable)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "key",
"function Redirect() {location.href = 'homePage.aspx';}
if(confirm('The items : "+sb.ToString()+" will arrive in 1 month.
Do you wish to continue?') == true){Redirect();};", true);
}
}
}
Everytime i click the button, it just passes like nothing.. never prompts eveb though IsNotAvailable is true when I add a breakpoint.
You can go for a simpler way,
Define the javascript function in the design/separate script file so that it accepts the name of item. eg. myFunction(itemName)
And in your CS file, simply add a call to that function,
if (IsNotAvailable)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "key",
"myFunction('" + itemName + "')
}
}
It will make things simpler and you would be able to confirm if this is a Javascript issue or a problem in how you are writing it through CS file.
Update:
Your first goal should be to make sure that your JS function is working for you, so before anything, add the following code in an empty html file and run it,
<script type='text/javascript'>
ItemNotInStock('item');
function ItemNotInStock(itemName)
{
var message = "The following items are no longer in stock :" + itemName + ".
Would you like to continue?";
if (confirm(message) == true)
{ location.href = "homePage.aspx"; }
}
If you redirect correctly then do what's mentioned below.
Define the following javascript in your design file(tested it locally, working for me in chrome,)
<script type='text/javascript'>
function ItemNotInStock(itemName)
{
var message = "The following items are no longer in stock :" + itemName + ".
Would you like to continue?";
if (confirm(message) == true)
{ location.href = "homePage.aspx"; }
}
In your C# code, add following line
if (IsNotAvailable)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "key",
string.Format("ItemNotInStock('{0}');", itemName);
}
}
Make sure your JavaScript code is executed by using breakpoints available in the developer tools of the browser of your choice, like Chrome Developer Tools: Breakpoints
BTW: Why do you create an instance of Merchandise if you instantly discard it with the next line?
I am trying to call a javascript simple alert function when I catch an exception in my C# code as follows:
inside my function:
try
{
//something!
}
catch (Exception exc)
{
ClientScript.RegisterStartupScript(typeof(Page), "SymbolError",
"<script type='text/javascript'>alert('Error !!!');return false;</script>");
}
Is there another way I can do this, because this doesn't show any alert boxes or anything??
It's because you'll get the error along the lines of:
Return statement is outside the
function
Just do the following, without the return statement:
ClientScript.RegisterStartupScript(typeof(Page), "SymbolError",
"<script type='text/javascript'>alert('Error !!!');</script>");
The above should work unless if it is inside update panel. For ajax postback, you will have to use ScriptManager.RegisterStartupScript(Page, typeof(Page), "SymbolError", "alert('error!!!')", true); instead.
Its the return, the below code works:
try
{
throw new Exception("lol");
}
catch (Exception)
{
ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Error!!!');</script>", false);
}
Try this
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SymbolError", "alert('error');", true);
Try to use the following:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "AnUniqueKey", "alert('ERROR');", true);
I use this code in an asp.net project
public void MsgBox1(string msg, Page refP)
{
Label lbl = new Label();
string lb = "window.alert('" + msg + "')";
ScriptManager.RegisterClientScriptBlock(refP, this.GetType(), "UniqueKey", lb, true);
refP.Controls.Add(lbl);
}
And when I call it, mostly for debugging
MsgBox1("alert(" + this.dropdownlist.SelectedValue.ToString() +")", this);
I got this from somewhere in the web, but was like a year ago and forgot the real original source
here are some related links:
Diffrent Methods to show msg box in Asp.net on server side - Coding Resolved
Create a Message Box in ASP.NET using C# - Blog Sathish Sirikonda