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()"
Related
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.
i have one textbox and one button both on a gridview , when user clicks on button i want to get the textbox text and save to database then clear the text! i used code below it works fine and saves to database but cant clear the textbox why ?
protected void sendcm_Click(object sender, EventArgs e)
{
try
{
Button sendcm = (Button)sender;
GridViewRow gvrow = (GridViewRow)sendcm.NamingContainer;
int ActivityTypeID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["ActivityTypeID"].ToString());
int SourceID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["SourceID"].ToString());
TextBox tt = (TextBox)activity.Rows[gvrow.RowIndex].FindControl("cmtextbox");
if (tt.Text != "")
{
BusinessLayer.StatusComment_Table ncm = new BusinessLayer.StatusComment_Table();
ncm.Id = Convert.ToInt32(Session["ID"].ToString());
ncm.Statusid = SourceID;
ncm.Statuscommentdate = System.DateTime.Now;
ncm.Statuscommenttext = tt.Text;
ncm.Save();
tt.Text = ""; // its not working !!!!
}
}
protected void Page_Load(object sender, EventArgs e)
{
SessionLable.Text = Session["ID"].ToString();
if (!IsPostBack)
{
getData();
}
}
public void getData()
{
activity.DataSource = BusinessLayer.Activity_Table.GetByProfileData(ID, -1, activity.PageSize);
activity.DataBind();
}
You need to do this at the UI level.
Use jquery.post to call the method that saves the data.
return something back to the $.post callback to tell jquery that the post s complete,
then do something like $('#mytextfield').val('')
assuming that the text box has an ID. I am assuming this is HTML?
you might need to rebind your grid because from the code that you posted it's not clear that where are you re binding your grid.
You need to enable AjaxPostback in your page. After that, in your Page_Load logic, include the code
if(IsPostBack){...}else{...}
So you can handle the construction of UI elements depending on whether this is a fresh new view of the page or a postback (page refreshed due to user clicking the button). UI elements are sent to the browser, after that, there is no way for the server to change it except to refresh the page itself.
The manual (and the one I recommend) way is to do this via jQuery postback. As pointed out in the other answer, you'll need to setup an endpoint for the client browser to connect. After the server has done its job, return the result to the client. Then use jQuery to update the textbox.
i did this to solve my problem !
<asp:TextBox ID="cmtextbox" type="text" clientid="cmtextbox" TextMode="MultiLine" placeholder="نظر دهید..." Rows="1" style="resize:none" class="form-control" runat="server"></asp:TextBox>
<asp:Button ID="sendcm" style="margin-top:2px;" OnClick="sendcm_Click" class="btn btn-success btn-sm pull-left " OnClientClick="ClearTextbox(this)" runat="server" Text="ارسال" />
</script>
<script type="text/javascript">
ClearTextbox = function (that) {
$(that).prevUntil('div.stop', '[ClientID="cmtextbox"]').val('');
}
</script>
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....
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"];
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.