On Button Click Does Not Fire Up The PostBackUrl Once - c#

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>

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.

<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>

formview with ajax modal popup extender

I have tried this several ways and none of them seem to work for me. I have a formview and when the user goes into the edit mode and then clicks update I want a modal popup to show so they can type a note as to what they changed.
Here is my code
<ajaxToolkit:ModalPopupExtender ID="SubmitButton_ModalPopupExtender"
runat="server" OkControlID="EditNoteButton" PopupControlID="EditNotePanel"
BehaviorID="MPE" BackgroundCssClass="modalBackground"
TargetControlID="DummyButton">
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="EditNotePanel" runat="server" CssClass="style105" Height="23px" style="display: none">
<asp:TextBox ID="EditNoteBox" runat="server" CssClass="style106" Height="68px" Width="223px">What Did You Change?</asp:TextBox> <br />
<asp:Button ID="EditNoteButton" runat="server" CssClass="style107" Height="29px" Text="Ok" Width="52px" CommandName="update" /> <br />
</asp:Panel>
C#
protected void ClientInformationForm_ItemCommand(Object sender, FormViewCommandEventArgs e)
{
//case statements
if (ClientInformationForm.CurrentMode == FormViewMode.Edit)
{
SubmitButton_ModalPopupExtender.TargetControlID = ((Button)ClientInformationForm.FindControl("SubmitButton")).UniqueID;
}
From what I have read that should work. I have tried showing it through javascript on clientclick. I have tried displaying it by calling modal.show() in the itemcommand but none of them are displaying it. Does it matter if the panel or popup are inside or outside the formview?
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack && Session["CurrentAccountId"] != null)
{
AddressTypeddl.DataBind();
ShippingAddressddl.DataBind();
AddressForm.DataBind();
}
if (ClientInformationForm.DataItemCount == 0)
{
ClientInformationForm.BackColor = Color.FromArgb(0xd9e2bf);
}
else
{
ClientInformationForm.BackColor = Color.White;
}
if (Session["CurrentAccountId"] == null)
{
NoteBox.Visible = false;
NewNoteButton.Visible = false;
NoteTypeddl.Visible = false;
NoteLabel.Visible = false;
NoteTypeLabel.Visible = false;
NewNoteLabel.Visible = false;
CreditCardView.Visible = false;
NewAccountButton.Visible = true;
AddressTypeddl.Visible = false;
AddressLabel.Visible = false;
AddressForm.Visible = false;
}
else
{
NoteBox.Visible = true;
NewNoteButton.Visible = true;
NoteTypeddl.Visible = true;
NoteLabel.Visible = true;
NoteTypeLabel.Visible = true;
NewNoteLabel.Visible = true;
CreditCardView.Visible = true;
NewAccountButton.Visible = false;
AddressTypeddl.Visible = true;
AddressLabel.Visible = true;
AddressForm.Visible = true;
}
}
So I just realized if I want people to keep posting I need to edit my original post and not just add a note, so hopefully this helps. Anyway, I still can't get this to work and I don't know what is causing my popup not to fire?
If you want to pop up the modal after the user makes their edits, I wouldn't use the ItemCommand event.
I haven't used FormViews much, mostly GridViews. But I'm assuming that the principles are mostly the same.
Have you tried showing the modal in the ItemUpdated event?
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.formview.itemupdated(v=vs.110).aspx
I haven't tried this before, but I'd like to think that something like this may work:
protected void ClientInformationForm_ItemUpdated(Object sender, FormViewUpdatedEventArgs e)
{
//capture ID of the updated record, and perhaps store it in a HiddenField that's in the modal
SubmitButton_ModalPopupExtender.Show();
}
Well after many days of trail and error I finally found out why this wasn't working. It came down to the dummy button. I was setting visible to false to hide the button and for some reason that doesn't work. Once I changed it to style= display:none; it fired fine. Weird that there was no error thrown it was just never popping up.

Maintain Tab index after post back

I have an Order page with 4 textboxes that are inside an ajax updatepanel. All the 4 have TextChanged events. None of the controls in this page have TabIndex property set. When I enter text in textbox1 & press the tab key, it causes postback, but the next focus is not on textbox2 as I want. The focus is on the page instead. Similarly with all the textboxes.
This Order page uses a master page.
Master page:
<form id = "form1" runat="server">
<asp:ScriptManager ID="ScriptManager1 " runat="server" />
Order page:
<asp:content id ="bodycontent" contentplaceholderID="maincontent" runat="server">
// 4 text boxes
</asp:content>
I cannot add another form or scriptmanager tag in the order page as it errors out saying there can be only instance of them.
So ,there is no FormOrder or ScriptManagerOrder in the Order page's code behind, but I would like to do something of the foll. way.
How can I do this.
protected void textbox1_TextChanged(object sender, EventArgs e)
{
//someFunction();
TextBox tb = (TextBox)FormOrder.FindControl("textbox2");
ScriptManagerOrder.SetFocus(tb);
}
Try this
protected void textbox1_TextChanged(object sender, EventArgs e)
{
//someFunction();
TextBox tb = (TextBox)FormOrder.FindControl("textbox2");
tb.focus();
}
Add following script in js file called i.e focus.js:
var lastFocusedControlId = "";
function focusHandler(e) {
document.activeElement = e.originalTarget;
}
function appInit() {
if (typeof(window.addEventListener) !== "undefined") {
window.addEventListener("focus", focusHandler, true);
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
}
function pageLoadingHandler(sender, args) {
lastFocusedControlId = typeof(document.activeElement) === "undefined"
? "" : document.activeElement.id;
}
function focusControl(targetControl) {
if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
var focusTarget = targetControl;
if (focusTarget && (typeof(focusTarget.contentEditable) !== "undefined")) {
oldContentEditableSetting = focusTarget.contentEditable;
focusTarget.contentEditable = false;
}
else {
focusTarget = null;
}
targetControl.focus();
if (focusTarget) {
focusTarget.contentEditable = oldContentEditableSetting;
}
}
else {
targetControl.focus();
}
}
function pageLoadedHandler(sender, args) {
if (typeof(lastFocusedControlId) !== "undefined" && lastFocusedControlId != "") {
var newFocused = $get(lastFocusedControlId);
if (newFocused) {
focusControl(newFocused);
}
}
}
Sys.Application.add_init(appInit);
Reference it using Scriptmanager like below:
<ajax:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<ajax:ScriptReference Path="~/Js/FixFocus.js" />
</Scripts>
</ajax:ScriptManager>
For more information check out below link:
http://couldbedone.blogspot.in/2007/08/restoring-lost-focus-in-update-panel.html
It's not a good practice to use server-side controls for a Tab. Why don't you use some jQuery/Bootstrap?
With your current approach you use to many useless Posts/Postbacks overloading your server with a useless work.

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

Categories

Resources