Inline C# code should be run only when clicked ASP.NET - c#

<a href='MainPage.aspx<%=Session["IDs"] = null%>'>Log out</a>
The above code is written in Navigation.ascx(Web Form User Control), and navigation is registered in almost all website pages. Now i want above code <%=Session["IDs"] = null%> to run only when i click on log-out.
Rite Now when i navigate to any page the above code runs every time. I am navigating through anchor tag.
**NEW CODE
<a runat="server" id="alogout" onclick="logout_click" href="#">Log out</a>
protected void logout_click(object sender, EventArgs e)
{
Session["IDs"] = null;
Response.Redirect("Login.aspx");
}

You have several options:
Add ID for the :
<'a runat="server" id="my_anchor" href='MainPage.aspx' onclick="anchor_click">Log out</a>
then add a method on the code behind:
protected void anchor_click(object sender, EventArgs e)
{
Session["IDs"] = null;
}
Change the href to another page that has Session["IDs"] = null and redirect to MainPage.aspx:
<a href='RedirectToMainPage.aspx'>Log out</a>

I have used option#2 as Ziv Weissman suggested.
Change the href value to another page.
Now in that page change the Session value to null
And redirect to certain page.

Related

How to get ispostback=true when <a href> object is clicked in c#

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.

How to set html link <a href> dynamically using C#

I have a menu in my web application like this
<div>
<ul>
<li><a href="http://localhost:52451/Voronezh/Settings.aspx">Settings</a</li>
<li><a href="http://localhost:52451/LoginPages/Welcome.aspx">Log out</a</li>
</ul>
</div>
I would like to set these href links dynamically if some special condition is true.
I've tried the following:
HTML code
<li><a runat="server" id="toSettings" onserverclick="toSettings_ServerClick">Settings</a></li>
C# code
protected void toSettings_ServerClick(object sender, EventArgs e)
{
if (condition)
toSettings.HRef = "http://localhost:52451/Voronezh/Settings.aspx";
else
{...}
}
but it doesn't work: I stay on the same page instead of moving to the Settings page.
Where is a mistake? What should be changed?
Thanks in advance.
Changing the HRef won't do much here - it changes the link, it doesn't have any direct effect on the page. Try Response.Redirect, I think this is what you're looking for. I.e:
// inside the if statement
Response.Redirect("Settings.aspx"); // note - this is the local path
Assuming this is ASP.NET C#
Redirect method from the HttpResponse should be what you are looking for.
Reference:
https://msdn.microsoft.com/en-us/library/a8wa7sdt(v=vs.110).aspx
If you want to build your menu dynamically in code behind you should probably use a <asp:Literal ID="menu" runat="server"/> tag in ASPX and fill it in the Page_Load event like
if (!Page.IsPostBack) {
menu.Text = GenerateMenu();
}
private string GenerateMenu() {
if (yourcondition) {
return "<div><ul><li></li></ul></div>";
} else {
}
}
Another alternative to doing a postback, executing the logic, and then doing a redirect would be to change the link tag to the hyperlink control, execute the logic on page load, and set the properties dynamically.
HTML:
<asp:HyperLink id="toSettings" Text="Settings" runat="server"/>
Code Behind
protected void Page_Load(object sender, EventArgs e) {
toSettings.NavigateUrl = "http://localhost:52451/Voronezh/Settings.aspx";
}
This way you could even change the text (use toSettings.Text = "Text to display";) or the visibility (use toSettings.Visible = false;) if needed.

Passing a value from a User Control to code behind

I'm trying to pass a value from a User Control to a code behind without luck. I can write the correct value (IDuser_uc) on the aspx page but I can't pass it to the code behind. Any tips?
User Control
protected void FormView_IDuser_DataBound(object sender, EventArgs e)
{
Label IDuserText = FormView_IDuser.FindControl("IDuserLabel") as Label;
IDuser_uc = Convert.ToString(IDuserText.Text);
}
ASPX page
<uc4:IDuser id="IDuser" runat="server" />
<% Response.Write(IDuser.IDuser_uc); // Here correct value %>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource_userConnections.SelectParameters["IDuser_par"].DefaultValue = IDuser.IDuser_uc ; // Here NO value
Response.Write("Connections :" + IDuser.IDuser_uc); // Here NO value
}
UPDATE
The problem was due to the fact that the User Control is run after the PageLoad which explains why I got an empty string. To solve the problem I used Page_PreRender instead of Page_Load on the code behind page.
Create a public method in your user control. When you post back the page have the Parent.aspx page call the user control method. Example....
In your User Control:
Public string GetUserControlValue()
{
return Label IDuserText;
}
In your Parent ASPX Pgae
var UserControlString = IDuser_uc.GetUserControlValue();

asp.net normal html input runat="server" return non-updated value in code-behind

I have edit server detail page called editServer.aspx. On page load, I retrieve data from database and set value to textbox. When user clicks save button, the value from textbox is empty or not updated to new value that users key in.
part of code in .aspx
<input type="text" class="form-control" id="serverRemarksTB" name="serverRemarksTB"
placeholder="general server remarks" runat="server"/>
<asp:Button ID="editPhysicalServerBtn" runat="server" Text="Save" class="btn btn-success"
style="padding-left:30px; padding-right:30px;" onclick="editPhysicalServerBtn_Click" />
in .aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
//code to retrieve data from database and store in server instance
serverRemarksTB.Value = server.remarks;
}
protected void editPhysicalServerBtn_Click(object sender, EventArgs e)
{
string remarks = serverRemarksTB.Value; //this is not updated.
}
For example, in database the server remarks is "do not shutdown". So when I open the .aspx page, I will see the textbox with "do not shutdown". When I change the value to "can shutdown" and click Save button, in aspx.cs server remarks value remains the same - "do not shutdown".
It's because everytime you load the page you override the value of the input with this line of code...
serverRemarksTB.Value = server.remarks;
and based on the ASP.NET Pipeline Lifecycle, Page_Load is executed first and then controls' event handlers. To avoid that you will need to run the above mentioned line of code only when the page first load...on a GET request and not on a POST request. You can change the Page_Load event handler like this...
protected void Page_Load(object sender, EventArgs e)
{
//code to retrieve data from database and store in server instance
if(!IsPostBack)
serverRemarksTB.Value = server.remarks;
}
Use IsPostBack clause or every time your page loads your textbox will be populated from database value .
When you click save button , it causes postback which causes your serverRemarksTB value again to
"do not shutdown".
if(!Page.IsPostBack)
{
serverRemarksTB.Value = server.remarks;
}
That's because your page_Load serverRemarksTB.Value = server.remarks;code is not wrapped in IsPostback block. So when you post your form back the value of the text box gets updated to database value. You should put your database code inside IsPostback check. Like
if(!IsPostBack)
{
serverRemarksTB.Value = server.remarks;
}
in the Page_Load method.

LinkButton doesn't Postback on first click in asp.net?

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.

Categories

Resources