I have a .aspx Webpage with a UserControl added on it.In UserControl when the LinkButton is clicked it do not Postback on first attempt. but when we click again it does the Postback and then only the page redirects don't know why?
Any idea?
In .ASPX Markup:
<asp:LinkButton ID="lnkCheckOut" runat="server"
CssClass="button orange" onclick="lnkCheckOut_Click">Checkout</asp:LinkButton>
In.cs file:
protected void lnkCheckOut_Click(object sender, EventArgs e)
{
if (Session["UserID"] != null)
{
lnkCheckOut.PostBackUrl = "~/checkout.aspx?type=checkout";
//Response.Redirect("~/checkout.aspx?type=checkout");
Session["IsQuoteAdded"] = "false";
}
//if not logged in user
else
{
lnkCheckOut.PostBackUrl = "~/login.aspx?returnUrl="+HttpUtility.UrlEncode(Request.RawUrl);
}
}
When i see markup in browser(using F12 in Chrome) on first click it shows:
<a id="ctl00_ContentPlaceHolder1_shpCart_lnkCheckOut" class="button orange" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$shpCart$lnkCheckOut','')">Checkout</a>
On Second Click:
<a id="ctl00_ContentPlaceHolder1_shpCart_lnkCheckOut" class="button orange" href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ContentPlaceHolder1$shpCart$lnkCheckOut", "", false, "", "login.aspx?returnUrl=%2fNew%2fMyBox.aspx", false, true))'>Checkout</a>
Note:I am not using any UpdatePanel in the Webpage or UserControl.
Help Appreciated!
Your code is not redirecting the page it has just assigning the URL. Use below codes to rectify that.
protected void lnkCheckOut_Click(object sender, EventArgs e)
{
if (Session["UserID"] != null)
{
//lnkCheckOut.PostBackUrl = "~/checkout.aspx?type=checkout";
Session["IsQuoteAdded"] = "false";
Response.Redirect(#"~/checkout.aspx?type=checkout");
}
//if not logged in user
else
{
Response.Redirect(#"~/login.aspx?returnUrl="+HttpUtility.UrlEncode(Request.RawUrl));
}
}
In your markup, there is no PostBackUrl. So on the first click, it will actually post back to the same page, and your event handler will run.
Then, in your event handler, you are setting the PostBackUrl.
So the second time somebody clicks the link, it will post to that URL. Your code is working as designed :)
Edit: I would suggest changing to Response.Redirect, but it's hard to know exactly what your code is supposed to do.
Same issue i was facing.
I have link button in grid view. when i clicked the link button its not postback on first click ,but when i clicked again it does.
Then i check my code properly and then i find that grid view is placed in update panel hence its not postback on first click.
So i would suggest please check the same.
Related
Lets preface this with the fact that I am learning ASP.NET C# and this is my first "real" project so there is a good chance I am missing something obvious, I apologize in advance.
I am working on a web page that displays three columns. The first is "Categories", a user should be able to select a category then have a list of items to choose from appear in the second column "Items". When they click an item the third column should show details about said item. For the most part this is a classic Master/Detail scenario except we take it a step further and do Master/Detail/Detail.
To achieve this I am generating dynamic buttons on Page_Load() in the "Categories" column. In addition I have added a debug line when the page loads, this is important later.
protected void Page_Load(object sender, EventArgs e)
{
//DB query to get categories omitted
for (int i = 0; i < categories.Rows.Count; i++)
{
Button btn = new Button();
btn.Click += new System.EventHandler(CategorySelected_Click);
btn.Attributes["runat"] = "server";
btn.ID = "CatSelBtn" + i;
btn.Attributes["data-categoryid"] = qry.GetCategories().Rows[i]["id"].ToString();
//And some other non-relevant attributes
CategoriesPane.Controls.Add(btn);
}
System.Diagnostics.Debug.WriteLine("Page Loaded");
}
As you may have noticed these buttons have a Click event handler that calls the method CategorySelected_Click(). These buttons all generate successfully and clicking on them results in that method being successfully called. This method is set up in a similar fashion, it grabs a list of items then generates buttons for the items, of course this needs to be done asynchronously so it doesn't reset the user's category selection, so this time it is all contained with an update panel.
C#
protected void CategorySelected_Click(object sender, EventArgs e)
{
//DB query to get items omitted
Button btn = (sender as Button);
string categoryid = btn.Attributes["data-categoryid"].ToString();
for (int i = 0; i < items.Rows.Count; i++)
{
if (items.Rows[i]["Category"].ToString() == categoryid)
{
Button ibtn = new Button();
ibtn.Click += new System.EventHandler(this.ItemSelected_Click);
ibtn.Attributes["runat"] = "server";
ibtn.ID = "ItmSelBtn" + i;
ibtn.Attributes["data-itemid"] = qry.GetItems().Rows[i]["id"].ToString();
//And again some none relevant attributes here
ItemsParent.Controls.Add(ibtn);
}
}
ItemsPanel.Update();
}
ASP
<div class="col-md-2 items-pane">
<asp:UpdatePanel ID="ItemsPanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="False">
<ContentTemplate>
<div id="ItemsParent" runat="server">
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="col-md-8 view-pane">
<asp:UpdatePanel ID="ItemDetailsPanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="False">
<ContentTemplate>
<div id="ItemDetailsParent" runat="server">
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
Again this generates a list of buttons for each item matching the correct category. No issue there, but this time I need the clicked button to call the third and final method which will display the details for the item. This is where things stop working. I assumed that because I was able to generate buttons successfully on Page_Load() that it would work the same inside an update panel. Right now the third method just contains a debug line to check if its firing at all.
protected void ItemSelected_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Item has been selected");
ItemDetailsPanel.Update();
}
In my output console in visual studio when I click on an Item Button control it writes Page Loaded indicating a successful postback but I am not seeing Item has been selected indicating that the third method is firing. I also inserted a breakpoint there but it is not being reached.
I initially thought I needed to add an asyncpostback trigger for each button generated to my update panel but that did not seem to resolve that issue, and because I can now see that Page_Load() is getting triggered I am pretty sure that isn't the issue. This leads me to believe that the click event is somehow not being registered. So my question to you is this: How do I make a dynamically generated button inside an update panel call a server side method? Any help is greatly appreciated.
You need to attach the event handlers on every postback.
It works for your categories-buttons, because the attaching is executed on every page load.
Do this for all the other items also, e.g. put in your Page_Load something like this:
foreach (var ctrl in ItemsParent.Controls)
{
Button ibtn = ctrl as Button;
if (ibtn != null)
{
ibtn.Click += new System.EventHandler(this.ItemSelected_Click);
}
}
I have 2 hrefs like below in asp.net 4.5:
</i>
</i>
where I have some process to do in page_load in c# like
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//loading data from db;
}
}
When I click on this a href, the page_load event is triggered and IsPostBack comes as false. Therefore, it is loading the data again and again whenever someone clicks previous or next page hrefs, causing a performance issue. I need to prevent this happening, meaning that I want IsPostBack = true after an href link is clicked. What is the best way to handle this issue?
I have tried to use onclientlick="return false;", it did not work.
I have tried to use asp:button and asp:linkbutton like below, did not work.
<asp:Button ID="btnPrev" runat="server" Text="left" OnClick="RedirectPreviousPage" />
protected void RedirectPreviousPage(object sender, EventArgs e)
{
var prevPage = CurrentPage == 1 ? -1 : CurrentPage - 1;
Response.Redirect("/Admin/" + prevPage);
}
What is the best solution? Any help or advise would be appreciated. I've checked lots of previous topics with related issue, but couldn't find a proper solution for my case. Apologies if I am causing a duplication. Regards.
Edit: also did not work.
<script>
function RedirectPreviousPage()
{
window.location.href = "/Admin/<%= prevPage %>";
}
</script>
</i>
Changing hrefs into "asp:LinkButton" and setting AutoPostBack property to true for those linkbuttons fixed my issue.
I am trying to change FailureText of Login control is IsApproved = false. But unable to do so. In watch it shows the text change when breakpoint hits the if condition. But when the page loads, it show the original result. Any suggestions please.
<asp:Login ID="LoginControl" runat="server" MembershipProvider="Xrm"
FailureText="Unable to login, please check your username and password"
FailureTextStyle-CssClass="alert alert-error" RenderOuterTable="False">
</asp:Login>
<%
if (IsPostBack && !Membership.GetUser(LoginControl.UserName).IsApproved)
{
LoginControl.FailureText = "Account is locked, please try after 10 minutes.";
}
%>
Thanks in advance
Created the LoginError event to move the IF condition there and it started working.
protected void LoginControl_LoginError(object sender, EventArgs e)
{}
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'm designing a page that has an Infragistics WebImageButton.
When clicking on that button I display a confirmation box.
If user clicks "OK", postback occurs that needs to trigger my click event, but it does not.
Here is what I have:
My webimagebutton:
<td><igtxt:webimagebutton id="btnHandle" runat="server" text="Process" usebrowserdefaults="False" cssclass="bodytext">
<clientsideevents click="confirmProcess"></clientsideevents>
<RoundedCorners MaxHeight="80" ImageUrl="ig_butXP1wh.gif" MaxWidth="400" HoverImageUrl="ig_butXP2wh.gif"
RenderingType="FileImages" PressedImageUrl="ig_butXP4wh.gif" DisabledImageUrl="ig_butXP5wh.gif"
FocusImageUrl="ig_butXP3wh.gif"></RoundedCorners>
</igtxt:webimagebutton>
</td>
My client-side function:
function confirmBoarding(oButton,oEvent)
{
var strMessage = "Are you sure you want to proceed?\nIf yes, press OK, otherwise CANCEL";
if(!confirm(strMessage))
{
oEvent.cancel = true;
return false;}
}
return;
}
My click event in code-behind:
private void btnHandle_Click(object sender, Infragistics.WebUI.WebDataInput.ButtonEventArgs e)
{
String here = "I'm here";//never gets hit
}
My code-behind method never gets hit.
What am I doing wrong?
Thank's
Make sure you have wired up the event. From the markup provided and the C# code there is no evidence that the event is wired up.