How to set html link <a href> dynamically using C# - 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.

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.

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

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

how change textbox text after clicking on a button inside a gridview

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>

Click Event of Dynamically generated Anchor Not Firing

I have an anchor on Lable Text.I am creating anchor with runat="server" dynamically on click of a button, It gets created as expected. I want to use its click event but it does not fire.
My code :
lblEmail.Text = email + " <a href='#' runat='server' class='crossicon' onclick='removebtn_Click'></a> ";
protected void removebtn_Click(object sender, EventArgs e)
{
}
How Can I create event for this button?I don't want to use JS, as in that case I will have to use a hidden field for new value
Adding markup/text to the label in that way wouldn't add the linkbutton or register the event to the control tree at the server. For that behavior of dynamically adding controls along with the server events to be achieved, you need to register the controls and events (as shown below)
aspx:
<asp:Panel runat="server" id="pnlEmail">
<asp:Label runat="server" id="lblEmail"/>
</asp:Panel>
aspx.cs:
In whichever event, you want to set the label text (along with the link)
lblEmail.Text = email;
LinkButton lnkbtnEmail = new LinkButton();
lnkbtn.Click += lnkbtn_Click;
lnkbtn.Text = "Dynamic Link";
pnlEmail.Controls.Add(lnkbtnEmail);
And the Handler would be
void lnkbtn_Click(object sender, EventArgs e)
{
// code for your dynamically generated link
}
By default, controls use __doPostBack to do the postback to the server. __doPostBack takes the UniqueID of the control (or in HTML, the name property of the HTML element). The second parameter is the name of the command to fire.
<a href='#' runat='server' class='crossicon' href="javascript:void(0);" onclick="__doPostBack('someuniqueid', '');></a>
System.Web.UI.Page already implements the IPostBackEventHandler interface by default, so you don't need to implement it on every page - it's already there.
You can override the RaisePostBackEvent method on the page like this:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
//call the RaisePostBack event
base.RaisePostBackEvent(source, eventArgument);
if (source == SomeControl)
{
//do something
}
}
I hope it will help you.
I don't think so it is created dynamically. Where is ID of that control. You have to Create Server side control and add it into some placeholder/panel e.t.c

Send data from javascript to code behind at first load

I am actually buidling a web application and I need to get data of the local environment of the machine viewing the application.To do this, I use a little javascript script such as:
<script language="javascript">
function GetUserName()
{
//Permits to get username of client machine
var wshell = new ActiveXObject("WScript.Shell");
var arpege = wshell.ExpandEnvironmentStrings("%USERNAME%");
document.getElementById("arpege").value=arpege;
}
</script>
<input type=hidden id="arpege" runat=server />
My problem is that this script is executed after the page is loaded and so I can't use it on the page load...
My code on the page load is:
protected void Page_Load(object sender, EventArgs e)
{
myConnection.ConnectionString = ActionSource.ConnectionString;
myConnection.Open();
String account = arpege.value;
...
}
But i just get "" in account...
Thanks for your help,
Quentin
Page_Load occurs on the server side before any data is being sent to the client.
you can't do that without initiating a new postback once the page is loaded.
Solution coming up...
EDIT:
So, it (might) be possible to achieve this using some jQuery
$(document).ready(function() {
var wshell = new ActiveXObject("WScript.Shell");
var arpege = wshell.ExpandEnvironmentStrings("%USERNAME%");
__doPostBack('__Page', arpege);
});
And catch it on the server side:
public void Page_Load(object sender, EventArgs e)
{
string arpege= Request["__EVENTARGUMENT"];
}
Worth's a shot!
A variant of the proposition made by Shai could be the following:
generate an asyncpostback on a hidden button.
Like that, the logic could be separated from the Page_Load, and
put instead in the handler attached to the input which generated the asyncpostback.
I don't like to put too much logic in the page_load event, i find it confusing.
the implementation will be a little more complicated though
Get the username server side in Page_Load instead of with an ActiveX control.
protected void Page_Load(object sender, EventArgs e)
{
myConnection.ConnectionString = ActionSource.ConnectionString;
myConnection.Open();
String account = User.Identity.Name;
// ...
}
Also, ActiveX only works in Internet Explorer - User.Identity.Name works on the server and therefor all browsers.
The ASPX code:
<body>
<form id="form1" runat="server">
<input type="hidden" id="hdnUser" runat="server" />
<input type="hidden" id="hdnRun" runat="server" value="true" />
<asp:Label ID="lblSayHello" runat="server" Text="I dont know you"></asp:Label>
</form>
<script type="text/javascript">
$(function () {
var run = $('#hdnRun').val();
if (run == 'true') {
var wshell = new ActiveXObject("WScript.Shell");
$('#hdnUser').val(wshell.ExpandEnvironmentStrings("%USERNAME%"));
$('#form1').submit();
}
});
</script>
</body>
The Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(hdnUser.Value))
{
hdnRun.Value = "false";
lblSayHello.Text = String.Format(#"Hello, {0}", hdnUser.Value);
}
}
The best (easiest) way that I know of sending data from the client to the server is to
1. Store it in an asp hidden field
2. Click an ASP button via javascript
3. Handle the data in the OnClick Event
For example:
ASPX Page
<asp:HiddenField ID="myHf" class="myHf" runat="server" />
<asp:Button ID="myButton" class="myButton" runat="server" OnClick="myButton_Click" style="display: none;" />
Javascript
function SendMyData(data) {
document.getElementByClassName('myHf').value = data;
document.getElementByClassName('myButton').click();
//I use classes since those won't change - IDs become really long and messed up
//in the actual page, and may change depending on where the element is placed.
}
CodeBehind
protected void myButton_Click(object sender, EventArgs e)
{
//Do whatever you want with myHf.Value
MyServerMethod(myHf.Value);
}
I think that doing it this way is better than using the Page_Load and submitting the form, just because if you are doing enough of these, the Page_Load method can get huge. But that's just my opinion.

Categories

Resources