deleting record when it shouldn't - c#

I am trying to show a confirmation box, which works perfectly with Confirm but doesn't work with my custom message box,
This works,
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton link = (LinkButton)e.Row.Cells[4].Controls[2];
if (link != null)
{
link.OnClientClick = "return confirm('Do you really want to delete?')";
}
}
}
BUT when i put this instead
link.OnClientClick = "ConfirmationBox()";
function ConfirmationBox()
{
$.blockUI({ message: $('#question'), css: { width: '275px' }
});
}
It shows message box but then it also deleting my record :'(
Still confused ? check this out,
Command field showing messagebox
Edit
<script type="text/javascript">
$(document).ready(function() {
$('#yes').click(function() {
$.unblockUI();
return true;
});
$('#no').click(function() {
$.unblockUI();
return false;
});
});
</script>

Look at the difference between the two OnClientClick events. The one that works properly returns a value, whereas the one that does not does not.
When the button is clicked, the button action is performed. The on-click action is also performed. However, if the on-click action returns false, the button's action is cancelled. Change
link.OnClientClick = "ConfirmationBox()";
to
link.OnClientClick = "return ConfirmationBox()";
and make ConfirmationBox() return false if the action is not confirmed.

The second option most probably does not return false, this is why your record is deleted in any case. You can verify it by changing it to :
function ConfirmationBox()
{
$.blockUI({ message: $('#question'), css: { width: '275px' }});
return false;
}
Not that this would prevent deleting the record, but also will not let you to delete it. You would need something that would return the result of the UI control.
Also you should modify the link :
link.OnClientClick = "return ConfirmationBox()";

As Jim said you have to have
link.OnClientClick = "return ConfirmationBox()";
ConfirmationBox should always return false. You need to have one more button which will perform the delete operation and you need to fire that button's click event if user press yes button. I hope that makes sense.

Related

Disable PostBack button asp and run server code

I'm trying to prevent my asp.net button to do PostBack as follow:
<asp:button runat="server".... OnClientClick="Confirm(); return false;" />
This is prevent button PostBack but that's isnt running also my OnClick button event.
How can i fix it?
What i'm trying to do is to display confirm message, but if the user click on 'No' the button do PostBack
Confirm function:
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);
}
My Button callback (that isn't calling while 'return false' append to OnClientClick:
public void OnButtonClicked(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
//my code
}
}
The OnClientClick event handler should return false only when you want to prevent the postback. The simplest way to do it would be:
<asp:Button runat="server" OnClientClick="if (!confirm('Do you want to save data?')) return false;" ... />
If you need more processing during the confirmation process, you can put it in your Javascript function which should return a boolean value:
<asp:Button runat="server" OnClientClick="if (!confirmSaving()) return false;" ... />
function confirmSaving() {
...
if (some condition) {
...
return true;
} else {
...
return false;
}
}
Note: we could simply return the value of the function instead of putting a condition inside OnClientClick. That solution fails for some controls however (see __doPostBack only works if there is a LinkButton, Calendar or WizardStep control on the page), while the conditional version works for all of them.

Custom Validation when TextBox has value and CheckBox does not

I have a situauation that I need to check on a button click if the user has entered a value into a textbox, but have not checked a checkbox. They need to be advised that they can not enter a value in the textbox without first checking the checkbox. I know I need to use a CustomValidator Control, but other than that I'm lost. Can anyone help me?
In OnClientClick event you can call a javascript method which will do this validation for you.
This should point you in the right direction.
I think the easiest way to do so will be enabling/disabling the textbox base on whether the checkbox is checked.
However, if you want to do the check on button_click, maybe just do checks on both the checkbox and textbox? And output error message to a label or something?
if(TextBox1.Text.Trim() != "")
if(!CheckBox1.Checked)
label1.Text = "Checkbox needs to be checked";
Or, you can do checks when TextBox1.Text has changed.
private void Textbox1_TextChanged(object sender, EventArgs e)
{
if(!CheckBox1.Checked)
label1.Text = "Checkbox needs to be checked";
}
You can implement this functality using javascript/Jquery.Set the onClientClick property of button as below:
<asp:Button ID="btnSubmit" runat="server" onClientClick="ValidateData();"/>
Below is the jquery code:
function ValidateData()
{
if(!$('#checkboxID').is(':checked') && $.trim($('#textBoxID').val())!='')
{
alert('Please check the checkbox before entering text');
}
}
You can try this...
First you must have a button like this...
<asp:Button ID="btnCheck" runat="server" CssClass="m-btn purple" Text="Check" onclintclick="Validate()"/>
Now we can write the validation script...
<script type="text/javascript" language="javascript">
function Validate() {
if(document.getelementid('checkbox1').checked==true)
{
if(document.getelementid('Textbox1').value=="")
{
//Write your code here..
}
}
else
{
alert('Please check the checkbox..');
}
}
</script>
Please feel free to mark as answer if it satisfies you....

How can I access asp.net button's "Text" in a code behind method?

In reference to the question of mine at deleting record when it shouldn't
How can I access asp.net button's "Text" in a code behind method?
Here's how button looks like:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:Button ID="HiddenButton" Text="" runat="server" OnClick="Deleting_Click" />
This is my code behind:
protected void Deleting_Click(object sender, EventArgs e)
{
I have already tried:
HiddenButton.Text = Request.Form["HiddenButton"].ToString();
and
Request["__EVENTARGUMENT"];
But nothing has worked, can someone show me the right direction please?
Edit
Can I use this any way? but not sure:
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
});
Update
What actually happening is, when user clicks on delete linkbutton in GridView this, happens,
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton link = e.Row.Cells[4].Controls[2] as LinkButton;
if(link.Text == "Delete")
link.OnClientClick = "return ConfirmationBox("+ ((DataRowView)e.Row.DataItem)["userID"].ToString() +")";
}
}
Now in JS I am catching the action Displaying a messagebox and always returning false, however I am setting text of hidden button so that I can send it to method in code behind for deleting a record using UserID
function ConfirmationBox(userID)
{
var elem = document.getElementById('<%= HiddenButton.ClientID %>');
elem.value = userID;
$.blockUI({ message: $('#question'), css: { width: '275px' }
});
return false;
}
Now I got the ID I needed and can make user choose yes or no, if user clicks yes then this happens,
$('#yes').click(function() {
$.unblockUI();
// $('<%= HiddenButton.ClientID %>').trigger('click');
__doPostBack('<%=HiddenButton.ClientID %>', "");
});
You can cast the sender to a button and get the information from that.
protected void Deleting_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
var text = btn.Text;
}
Update
When choosing (Cast)object vs object as object see Direct casting vs 'as' operator?
Update 2
When you want to pass some arguments through to your code which are set via JavaScript, you can pass them through with the EVENTARGUMENT
So when calling __doPostBack('',''); You can set it here. In your case you need to update your code to be;
__doPostBack('<%=HiddenButton.ClientID %>', 'Your Argument Here');
Then within your Deleting_Click method, you can get the argument;
string parameter = Request["__EVENTARGUMENT"];

Confirm for Linkbutton before performing delete in asp.net

I have a delete Linkbutton in my asp.net form. When the user clicks the button it will delete the contents from my db, which has been coded in the OnClick() of the button. But before that I need to have a confirm box which has yes or no options. How do I go about the deletion if the user clicks on "yes" and restrict deletion if user clicks on "no"? My problem is that onclick and onclientclick do not work together. Please help me ..Here is the sample code..
Where do I place the following script?
<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 delete data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
Code Behind:
protected void Mark_Click(object sender, EventArgs e)
{
a.Delete(name);
}
Use following code:
OnclientClick="return Confirm()"
Return true/false from Confirm() function, if Confirm() return true then postback will happen otherwise not.
Refer online sample to test this
Note:
We have used Confirm() in upper case because post has user defined function Confirm(). so please don't confuse with inbuilt function confirm() of java script.
use OnClientClick="return confirm()"

null element id for DataGrid ButtonColumns

I have a bit of JavaScript in one of my pages that avoids the problem of users double-clicking buttons on a form and causing double submissions during asynchronous postbacks:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
var btn;
function InitializeRequest(sender, args) {
document.body.style.cursor = "wait";
var btnId = args._postBackElement.id;
btn = document.getElementById(btnId);
if (btn != null && (btn.type == "button" || btn.type == "submit"))
btn.disabled = true;
}
function EndRequest(sender, args) {
document.body.style.cursor = "default";
if (btn != null) btn.disabled = false;
}
This isn't working with DataGrid ButtonColumns. document.getElementById(btnId) returns null for those.
If I use a TemplateColumn and put a Button control inside, that works fine.
Looking at the HTML that gets rendered for the DataGrid, I can see that ASP.NET isn't outputting an onclick for the ButtonColumn, where it does do so for a Button inside a TemplateColumn:
ButtonColumn:
<input type="submit"
name="ctl00$placeholderContent$dgCommittees$ctl03$ctl00"
value="Edit" />
Button in TemplateColumn:
<input type="submit"
name="ctl00$placeholderContent$dgCommittees$ctl03$cmdDelete"
value="Delete"
onclick="return confirm('Are you sure you wish to delete this committee?');
WebForm_DoPostBackWithOptions(
new WebForm_PostBackOptions("ctl00$placeholderContent$dgCommittees$ctl03$cmdDelete", "", true, "", "", false, false))"
id="ctl00_placeholderContent_dgCommittees_ctl03_cmdDelete" />
Obviously the answer to "how do I make this work?" is to simply replace all my ButtonColumns with Buttons in TemplateColumns.
I'm curious if anyone knows why ASP.NET renders ButtonColumns this way though, and if there's some way to get it to render them the same as Buttons.
MS has a standard implementation of bound fields, which does not set ID or attributes for ButtonColumn created buttons.
To be a bit more specific, whenever a grid creates cells and sub-sequentially buttons, it calls InitializeCell:
public override void InitializeCell(TableCell cell, int columnIndex, ListItemType itemType)
{
base.InitializeCell(cell, columnIndex, itemType);
if ((itemType != ListItemType.Header) && (itemType != ListItemType.Footer))
{
WebControl child = null;
if (this.ButtonType == ButtonColumnType.LinkButton)
...
else
{
child = new Button {
Text = this.Text,
CommandName = this.CommandName,
CausesValidation = this.CausesValidation,
ValidationGroup = this.ValidationGroup
};
}
...
cell.Controls.Add(child);
}
}
As you can see, that's all there is to a button.
If you want it to have IDs and "onclick" attributes, you could use something like this:
protected void grid_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//assuming that a first cell is a ButtonField
//note that in edit mode a button may be at some other index that 0
Button btn = e.Row.Cells[0].Controls[0] as Button;
if (btn != null)
{
btn.OnClientClick = "return confirm('are you sure?')";
btn.ID = "myButtonX";
}
}
}
I would recommend you to use JQuery to add event handlers on your buttons. Here is a sample:
function onclick () {
alert("1");
}
$(function () {
$("input[type='submit']").click(onclick);
});
This code will attach the onclick function to the onclick event for all input elements of type submit when the DOM is ready.
The unobtrusive JavaScript technique may interest you.
I would like to mention that Microsoft supports JQuery, and they will make support for it in upcoming versions of Visual Studio. For more information please visit http://live.visitmix.com/.

Categories

Resources