call OnClientClick and Onclick together in c# Button Event - c#

I have a Asp.Net c# application in which, having Logout Button on mAsterpage.
I am trying to alert confirmation window on click of LogOut. If i choose Yes, then I will redirect it into Log-in Page.
So I have tried below. OnClient Click I called below JavaScript Function.
<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>
On Button Click I have wriiten Below code.
protected void ImgbtnLogOut_Click(object sender, ImageClickEventArgs e)
{
try
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
Session.Clear();
Session.Abandon();
Response.Redirect(ConfigurationManager.AppSettings["LogoutURL"].ToString());
//Server.Transfer(ConfigurationManager.AppSettings["LogoutURL"].ToString());
}
else
{
//Do Nothing
}
}
catch (Exception ex)
{
}
finally
{
}
}
I am getting an error Unable to evaluate Expression, The code is Optimized....error in below line. And Page is not being redirected to required page.
Response.Redirect(ConfigurationManager.AppSettings["LogoutURL"].ToString());
can anyone please suggest, how can i achieve that.

This confirm box help you to get correct response with having Ajax.
java script code for geting confirm value.
<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 proceed continue ?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
On C# Code for geting exect data.
string confirmValue = Request.Form["confirm_value"];
string[] Value_Confirm = confirmValue.Split(',');
if (Value_Confirm[Value_Confirm.Length-1] == "Yes")
{}
or check here : http://www.codeproject.com/Answers/1070495/Ask-yes-no-cancel-window-in-csharp#answer6

Related

C#, ASP.NET: how to get a confirm message box from server side code when a condition is met

I have a button in my page which is used to save data of gridview which is dynamically populated. Before saving I want to check some condition. The javascript function is as follows:
<script type="text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("This will completely delete the project. Are you sure?")) {
confirm_value.value = "Yes";
}
else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
<asp:Button runat="server" ID="lnkBtn" onClick="lnkBtn_Click" onClientClick="Confirm()"></button>
The code behind is as follows:
protected void lnkBtn_Click(object sender, EventArgs e)
{
string str=gdView.HeaderRow.Cells[8].Text;
System.Web.UI.WebControls.TextBox txtID = (System.Web.UI.WebControls.TextBox)gdView.Rows[0].Cells[8].FindControl(str);
if (txtID.Text != "")
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
MyAlert("Yes clicked");
}
else
{
MyAlert("No clicked");
}
}
else
{
MyAlert("No Text found.");
}
}
Now the problem is since I have the function Confirm() in the onClientClick event, the confirm dialog appears the moment the user clicks the button, instead it should appear only when a string is found in txtID.
I tried to modify the code by removing the onClientClick event as follows:
<asp:Button runat="server" ID="lnkBtn" onClick="lnkBtn_Click" ></button>
protected void lnkBtn_Click(object sender, EventArgs e)
{
string str=gdView.HeaderRow.Cells[8].Text;
System.Web.UI.WebControls.TextBox txtID = (System.Web.UI.WebControls.TextBox)gdView.Rows[0].Cells[8].FindControl(str);
if (txtID.Text != "")
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "confirm", "Confirm();", true);
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
MyAlert("Yes clicked");
}
else
if (confirmValue == "No")
{
MyAlert("No clicked");
}
}
}
Here also it is not working properly. The confirmValue is getting the value but using it only during the subsequent click of the button. It is not passing value stored during the present click event instead the previously stored value is passed to if block. Please help to find what should I do get it right.
Thanks.

How can I conditionally prevent a form from submitting with server-side/code-behind?

When my "submit" (Save) button is clicked, one thing it does is verifies that the two "totals" vals match, and returns if they don't, fingerwagging the user with a red 'bad boy!' message:
message = new LiteralControl();
AddVerticalSpace();
Controls.Add(message);
decimal? paymentTot = TryConvertToDecimal(boxPaymentAmount.Text);
if ((null == paymentTot) || (paymentTot < 0))
{
paymentTot = 0M;
}
decimal? grandTot = TryConvertToDecimal(boxGrandTotal.Text);
if ((null == grandTot) || (grandTot < 0))
{
grandTot = 0M;
}
if (grandTot != paymentTot)
{
AddVerticalSpace();
message.Text = "<span style='color:red'>Total and Payment Total do not match; Please enter the same amount for both values and try again.</span>";
return;
}
What I intend with the "return" is that the submit is aborted; yet, with the code above, the form is still submitted - it reverts to its initial appearance/state. How can I conditionally prevent this automatic submit behavior?
UPDATE
This is for Tyree Jackson:
Here's the server-side save button. First, it is conditionally dynamically created and configured thus:
if (AnyCheckboxSelected())
{
// Create Save button
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save";
btnSave.Click += new EventHandler(btnSave_Click);
this.Controls.Add(btnSave);
AddVerticalSpace();
}
...and here is the event handler:
protected void btnSave_Click(object sender, EventArgs e)
{
LiteralControl message = null;
try
{
fullAddressChosen = rbFullAddress.Checked;
paymentToAnIndividualDropDownChosen = rbPaymentToIndividual.Checked;
paymentToAVendorDropDownChosen = rbPaymentToVendor.Checked;
message = new LiteralControl();
AddVerticalSpace();
Controls.Add(message);
decimal? paymentTot = TryConvertToDecimal(boxPaymentAmount.Text);
if ((null == paymentTot) || (paymentTot < 0))
{
paymentTot = 0M;
}
decimal? grandTot = TryConvertToDecimal(boxGrandTotal.Text);
if ((null == grandTot) || (grandTot < 0))
{
grandTot = 0M;
}
if (grandTot != paymentTot)
{
AddVerticalSpace();
message.Text = "<span style='color:red'>Total and Payment Total do not match; Please enter the same amount for both values and try again.</span>";
return;
}
ConditionallyCreateList();
SaveInputToList();
listOfListItems = ReadFromList();
message.Text = "Saving the data has been successful";
// Re-visiblize any rows with vals
if (RowContainsVals(3))
{
foapalrow3.Style["display"] = "table-row";
}
if (RowContainsVals(4))
{
foapalrow4.Style["display"] = "table-row";
}
if (RowContainsVals(5))
{
foapalrow5.Style["display"] = "table-row";
}
if (RowContainsVals(6))
{
foapalrow6.Style["display"] = "table-row";
}
AddVerticalSpace();
//CreatePDFGenButton();
GeneratePDFAndMsg();
btnGeneratePDF.Visible = true;
AddVerticalSpace();
GenerateLegalNotice();
}
catch (Exception ex)
{
message.Text = String.Format("Exception occurred: {0}", ex.Message);
}
}
First Default.aspx source:
<script type="text/javascript" language="javascript">
function validateData() {
var payment = parseFloat(document.getElementById('boxPaymentAmount').value).toFixed(2);
var total = parseFloat(document.getElementById('boxGrandTotal').value).toFixed(2);
if (payment == null) payment = 0;
if (total == null) total = 0;
if (payment == total) {
return true;
} else {
alert('Total and Payment Total do not match. Please enter the same amount for both values and try again!');
return false;
}
}
</script>
<asp:TextBox ID="boxPaymentAmount" runat="server"></asp:TextBox><br />
<asp:TextBox ID="boxGrandTotal" runat="server"></asp:TextBox><br />
<asp:Button ID="btnSave" runat="server" Text="Button" OnClientClick="return validateData();" OnClick="btnSave_Click" />
And code for Default.aspx.cs:
public partial class Default : System.Web.UI.Page
{
protected void btnSave_Click(object sender, EventArgs e)
{
//TODO: do your stuff here...
}
}
If you are talking about preventing a form from submitting in a web browser, you should use client side code (i.e. JavaScript) for that. Even if there was a way to do it in code behind, it would just be translated into client side code. Otherwise, the form will submit even if it retains the edited values.

How to get listbox id inside the listview in javascript

I want to to get listbox id inside the listview in javascript.
This is my Javascript:
<script>
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(
function (sender, e) {
var control = $find('<%= results.ClientID %>');
if (e.get_postBackElement().id =="<%=this.results.ClientID%>") {
$get("divvv").style.display = "none";
}
else {
$get("divvv").style.display = "block";
}
});
</script>
results is my listbox id but it is in the listview so that i couldn't get the listbox it directly as specified above.It shows Error.
Please hel me.Thanks in advance
i havent tested but you can try this
function (sender, e) {
var control = $find('<%= ((ListBox)MyListView.FindControl("myListBox")).ClientID %>');
if (e.get_postBackElement().id =='<%= ((ListBox)MyListView.FindControl("myListBox")).ClientID %>') {
$get("divvv").style.display = "none";
}
else {
$get("divvv").style.display = "block";
}

How to get the value of OK and CANCEL from alertbox

I want to generate an alert box on button click. I have written like this
protected void btn_submit_click(object sender, ImageClickEventArgs e)
{
btn_submit.OnClientClick = #"return confirm('Student has not completed all the steps? Are you sure you want to submit the details?');";
bool type = false;
if(type==true)
{
//If clicks OK button
}
else
{//If clicks CANCEL button
}
}
Alert box comes correctly. But how could I get the values from code behind?please help.
When confirm returns false, then there is no postback since the click event in the javascript is cancelled. If you want to have the postback after clicking cancel you need to change your code a little:
serverside:
protected void Page_Load(object sender, System.EventArgs e)
{
btn_submit.Click += btn_submit_click;
btn_submit.OnClientClick = #"return getConfirmationValue();";
}
protected void btn_submit_click(object sender, ImageClickEventArgs e)
{
bool type = false;
if(hfWasConfirmed.Value == "true")
{
//If clicks OK button
}
else
{//If clicks CANCEL button
}
}
on the client:
<asp:HiddenField runat="server" id="hfWasConfirmed" />
<asp:Panel runat="server">
<script>
function getConfirmationValue(){
if( confirm('Student has not completed all the steps? Are you sure you want to submit the details?')){
$('#<%=hfWasConfirmed.ClientID%>').val('true')
}
else{
$('#<%=hfWasConfirmed.ClientID%>').val('false')
}
return true;
}
</script>
</asp:Panel>
u can try this also
protected void BtnSubmit_Click(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (grdBudgetMgr.Rows.Count > 0)
{
if (confirmValue == "Yes")
{
}
}
}
<script type="text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Are you sure Want to submit all Budgeted Requirement ?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>

How to call Javascript from C# PageLoad?

I want to ask How to call javascript from C# page load.
My Javascript is
function Hide(lst) {
if (document.getElementById) {
var tabList = document.getElementById(lst).style;
tabList.display = "none";
return false;
} else {
return true;
}
}
and want to call from pageload
if (dtSuperUser(sLogonID).Rows.Count < 1)
{
//Call Javascript with parameter name tablist
}
thanks
Actually, you can use pageOnload event to do so.
Like this.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.ClientScript.RegisterStartupScript(this.GetType(), "show", "<script>document.getElementById('Your element').style.display = 'block'</script>");
}
else
{
this.ClientScript.RegisterStartupScript(this.GetType(), "show", "<script>document.getElementById('Your element').style.display = 'hidden'</script>");
}
}
String csName = "myScript";
Type csType = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
cs.RegisterClientScriptBlock(csType, csName,
string.Format("Hide({0})", lst.ClientID));
}
RegisterStartupScript("Hide", string.Format(#"if (document.getElementById) {
var tabList = document.getElementById('{0}').style;
tabList.display = 'none';
return false;
} else {
return true;
}",lst));
Or if you already have the Javascript function rendered in the Markup
RegisterStartupScript("Hide",string.Format("Hide('{0}');",lst));
Are you using webforms or MVC? If using webforms check:
http://msdn.microsoft.com/en-us/library/Aa479011
Page.RegisterStartupScript("MyScript",
"<script language=javascript>" +
"function AlertHello() { alert('Hello ASP.NET'); }</script>");
Button1.Attributes["onclick"] = "AlertHello()";
Button2.Attributes["onclick"] = "AlertHello()";

Categories

Resources