JavaScript confirm from code behind C# - c#

I have a button on my aspx page. I want to use javascript confirm before continuing execution when clicking on that button. I can do it easily if i am writing javascript in aspx page itself . But my problem is each time the confirm message may be different. I need to check various condition to generate appropriate confirm message.
Can I call confirm in my code behind, so that I can construct confirm message from there?
What I'm trying is:
protected void Button1_Click(object sender, EventArgs e)
{
//just the algorithm given here
string message=constructMessage(); \\ its just a function to construct the confirm message
if(confirm(message)) // i know i cant use javascript in code behind direct. How can i do this
{
//do something
}
else
{
// do nothing
}
}

protected void Button1_Click(object sender, EventArgs e)
{
string message=
"if(confirm("+message+"))
{
//do something
}
else
{
// do nothing
}";
this.ClientScriptManager.RegisterStartupScript(typeof(this.Page), "warning", message, true);
//Prints out your client script with <script> tags
}
For further reference on ClientScriptManager

I just got this link which describes different ways of calling javascript
http://www.codedigest.com/Articles/ASPNET/314_Multiple_Ways_to_Call_Javascript_Function_from_CodeBehind_in_ASPNet.aspx
may be this will help..

Related

Button click event error

Having just added a new button in my web application, I get an error when clicking on it, and I'm wondering if this is related to misplaced code. I will describe what/where I did, briefly. Thanks very much.
In ascx file:
<asp:Button ID="btn_rezerv" runat="server" Text="Reserve film" OnClick="btn_rezerv_Click"/>
In the ascx.cs file:
namespace CinProj.UserControls
{
public partial class FilmsList : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
PopulateControls();
}
private void PopulateControls()
{
string categId = Request.QueryString["CategID"];
string filmId = Request.QueryString["FilmID"];
....
if (categId != null)
{
.....
}
if (filmId != null)
{
......
Button btn_rezerv = (Button)item.FindControl("btn_rezerv");
}
}
protected void btn_rezerv_Click(object sender, EventArgs e)
{
string fid = Request.QueryString["FilmID"];
ShoppingCartAccess.AddItem(fid);
}
}
}
"Server Error in '/' Application.
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. "
Another problem could be because your PopulateControls method should probably only be called when during the Page Load when it's not a PostBack. I can't tell from above, but to me it looks like it only needs done on Load. Try wrapping that call with this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateControls();
}
}
It's likely the result of making some sort of client change that the server doesn't know about. Many times this is the result of changing values in a dropdown in JavaScript, for example.
To fix, you could:
Do away with using JavaScript for said modification
Use an UpdatePanel and add your control to it. If the client needs to make a change, trigger the UpdatePanel's update in order for the control's viewstate to update.

Getting a Confirmation Box to appear and get its value in the code behind

Here's what I want to do. I have a form that the user fills out (creating sections and subsections) and when they click save, I want to check the database to see if they have named a section the same as one that already exists. If they have, I want to get a confirmation from them to let them know they wil create a duplicate if they proceed. If they click yes, I need to continue, else I need to abort. Here is some psuedocode for what I have so far.
protected void SaveButton_Click(object sender, EventArgs e)
{
try
{
if (CheckForDuplicates())
{
//proceed normally
}
}
}
private bool CheckForDuplicates()
{
//check database
if (/*there are duplicates*/)
{
string message = "A duplicate name exists. Would you like to continue?";
string scriptString = "<script language='javascript'
type='text/javascript'>" + "return confirm('" + message + "');</script>";
ScriptManager.RegisterStartupScript(this, this.GetType(),
"script", scriptString, false);
//here i would like to return their confirmation
}
}
}
return true;
}
All help is appreciated and thanks in advance!
Add Javascript such that if user confirms, you can call the JavaScript __doPostBack('','UserConfirmed'); function. Just add the logic in your codebehind along with your confirmation logic that you are registering with the ScriptManager . When the postback occurs, you can then check to ensure that the postback was, in fact, initiated by the user's confirmation (as opposed to some other action on the page):
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
//if parameter equals "UserConfirmed"
// User confirmed, so do whatever
//
}
Information on __doPostBack: Understanding the JavaScript __doPostBack Function

Run a javascript on postback in c#

I used the below manner to run a JavaScript upon postback and it worked fine for me.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>document.getElementById('apDiv1').style.visibility = 'hidden';</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>function show()</script>");
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>document.getElementById('apDiv1').style.visibility = 'visible';</script>");
}
}
The above code worked fine and now I want to try something like below.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"verify","<script type='text/javascript'>verify1();</script>");
}
else
{
}
}
in the above code verify1() is a JavaScript linked externally to ASPX page. I am unable to execute verify1() function using this code. And verify1() function works fine when placed as <body onload="verify1();"> Is there any syntax error(s) in my above code?
this may help you,
Page.ClientScript.RegisterStartupScript(this.GetType(), "verify", "verify1()", true);
Maybe that script is being executed before verify1()'s function definition. By the time body.onload fires, the main page has completed parsing and all external scripts have been loaded, which is why it works in that scenario.
Can you use jquery? One option is to use jQuery's onload functionality, which won't be executed until everything is intialized:
$( function() { ...my startup code... });

Continue execution of the code after alert message from clientside

I've to send mail using webappplication.All works fine but i've to show a confirm message if attachments are not selected.In that confirm box when ok is clicked execution of the code should continue,when cancel button is clicked it should return.
This is my code
Code behind
protected void btnSend_Click(object sender, EventArgs e)
{
string str = "Are you sure, you want to proceed without attachment?";
this.ClientScript.RegisterStartupScript(typeof(Page), "Popup", "ConfirmApproval('" + str + "');", true);
...Send mail code goes here
}
ASPX
function ConfirmApproval(objMsg)
{
if(confirm(objMsg))
{
alert("execute code.");
return true;
}
else
return false;
}
It works fine, ie when ok button is clicked an alert "execute code" is displaying.Instead of displaying alert i want to continue execution of the code.How will we do that from client side ???
try this code,
protected void Page_Load(object sender, EventArgs e)
{
btnSend.Attributes.Add("onclick","return confirm('execute code');");
}
You need to use confirm("execute code") instead of 'alert'. Hope that helps :)
var agreed = confirm("execute code");
if(agreed) {
//do something
} else {
return false;
}
I am showing you one brute force way to do that.
put that code behind in the page_load(sender, e) of any web page you create. Now call it through XHR.
(this may be a bad reply).

how to write/code javascript(mouseover event) using c# methods/ c# code

note
yes client side must be java script but my qustion is not that.
i am asking that can i use c# language to implement "actions" fired on "click side events" such as mouse over
the reason for this stupid question is that i remember some syntax of registering functions for particular events of formview, which are call when the event occurs (yes there ispostback involved"
is something like the above possible for client side events using c# or even vb.net
heres a scrap of what i am trying to ask
protected void Page_Load(object sender, EventArgs e)
{
Label3.Text = "this is label three";
Label3.Attributes.Add("OnMouseOver", "testmouseover()");
}
protected void testmouseover()
{
Label4.Text = "this is label 4 mouse is working!!";
}
That is not possible.
You can use AJAX, but you cannot use AJAX to directly manipulate the DOM.
You can use an UpdatePanel, but not (easily) for mouse events.
You can use Script#, which converts C# into Javascript.
However, it would have nothing to do with server-side code
Does ClientScript.RegisterClientScriptBlock() have what you need?. Check here
You can do this by using page methods.
protected void Page_Load(object sender, EventArgs e)
{
Label3.Text = "this is label three";
Label3.Attributes.Add("OnMouseOver", "testmouseover()");
}
[webmethod]
public static void testmouseover()
{
// Implement this static method
}
and then on client side do this:
<script type='javascript'>
function testmouseover()
{
PageMethods.testmouseover();
}
</script>

Categories