Disable PostBack button asp and run server code - c#

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.

Related

On Button Click Does Not Fire Up The PostBackUrl Once

This seems to be an easy one but got stuck on it last few hours. I've a search button that fires up PostBackUrl. The issue is it only fires up when I click the search button for the second time. Here what I did:
Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Page.Title = "View Cities - CcmApp";
if (!IsPostBack)
{
BindGridView(0);
BindPager(0);
GetCountries();
}
}
protected void SearchButton_Click(object sender, EventArgs e)
{
City aCity = new City();
aCity.CityName = nameTextBox.Text;
if (nameTextBox.Text.Length == 0 && radioCityName.Checked == true)
{
labelMsg.Visible = true;
labelMsg.Text = "No search term given";
}
else
{
SearchButton.PostBackUrl = GetDefaultUrl();
}
BindGridView(0);
BindPager(0);
}
public string GetDefaultUrl()
{
return "SearchCity.aspx?SearchTerm=" + nameTextBox.Text;
}
Default.aspx:
<asp:LinkButton ID="SearchButton" runat="server" Text="Search" ValidationGroup="vdGroup"
CssClass="btn btn-primary" OnClick="SearchButton_Click"></asp:LinkButton>
I am not sure what causes it click second time to get the url. Is there any way to get over it?
Note: I am expecting to get the following output in the url -
http://localhost:1234/UI/SearchCity.aspx?SearchTerm=a. But works only on second button click. When I click for the first time, I get this - http://localhost:1234/UI/SearchCity.aspx
The PostBackUrl url on the button is only set AFTER the first PostBack. If you would set it in Page_Load for example you will see that it will work on the first PostBack.
If you want the ?SearchTerm= in the url only when there is content in nameTextBox you could use Response.Redirect or accept that there is no data in ?SearchTerm=.
Better still check on the Clientside if nameTextBox has text and prevent the button click using a Validator.
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="/Default.aspx?SearchTerm=" ValidationGroup="mySearch">Search</asp:LinkButton>
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="nameTextBox" ClientValidationFunction="checkLength" ValidateEmptyText="true" ErrorMessage="Min. 3 characters required" ValidationGroup="mySearch"></asp:CustomValidator>
<script type="text/javascript">
function checkLength(oSrc, args) {
var v = document.getElementById("<%=nameTextBox.ClientID %>").value;
if (v.length < 3) {
args.IsValid = false;
} else {
$("#<%=LinkButton1.ClientID %>").attr("onclick", $("#<%=LinkButton1.ClientID %>").attr("onclick").replace("?SearchTerm=", "?SearchTerm=" + v));
args.IsValid = true;
}
}
</script>

<a> tag problems and code behind problems

I got a problem, that i can't find the solution for.
Code
<a runat="server" href="#" onclick="login_box();">
<asp:Label ID="LabelLogin" runat="server" Text=""></asp:Label>
</a>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserId"] == null)
{
LabelLogin.Text = "Login";
}
else
{
LabelLogin.Text = "Logud";
}
}
It's okay, but now the problem is.
That i now want this one too on the 'a' tag's onclick, but it already got an "onclick" that opens the login box, this one checks for logged in or not, and if you aren't logged in, then it should open the "onclick login_box();" and if not, then it should logout.
This is used when you click on the either "login" or "logout".
I need a solution, for how i execute "onclick login_box" in code behind. And what i should do for the clicks, is it possible that i should move "login_box" to "onclientclick" and then i can use the "onclick" ?
if (Session["UserId"] == null)
{
//Opens the login box
}
else
{
Session.Abandon();
Response.Redirect("~/default.aspx");
}
This is how you can call JavaScript function in C#
public string functionname()
{
Page page = HttpContext.Current.CurrentHandler as Page;
page.ClientScript.RegisterStartupScript(typeof(Page), "CallMyClick", "<script type='text/javascript'>login_box();</script>");
}
Accessing ASP.NET Session variable using Javascript:
<script type="text/javascript">
function LoginLogOut()
{
var userId = '<%= Session["UserId"] %>';
if(userId != undefined)
{
document.getElementById("giveIdToAnchroTag").onclick = function (){LoginFunction();};
}
else
{
document.getElementById("giveIdToAnchroTag").onclick = function (){logOutFunction();};
}
}
</script>

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"];

deleting record when it shouldn't

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.

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()"

Categories

Resources