Make Control Visible/InVisible in ASP - asp.net

I have this hyperlink called “SEND” in a ASP page called Home and here it is:
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# Eval("Post_ID", "~/RCA.aspx?Post_ID={0}") %>'
Text="SEND"></asp:HyperLink>
</ItemTemplate>
when the user clicks the hyperlink it goes to another page called RCA and in this page there is a Button and here it is the code:
<asp:Button ID="btnRCA" runat="server" onclick="Button1_Click"
Text="Assign RCA" Width="147px" />
so I want this button to be visible only when clicked the hyperlink in the HOME page. I am planning to have another button or control in the RCA page that will make it invisible when clicked or before someone leaves the page they have to make it invisible the Button by clicking some other control. can someone help me with this? thanks

Use a QueryString parameter.
Home.aspx
//When linked to RCA.aspx from Home.aspx, a parameter called ShowButton=1 is included
//in the URL.
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# Eval("Post_ID", "~/RCA.aspx?Post_ID={0}&ShowButton=1") %>'
Text="SEND"></asp:HyperLink>
RCA.aspx
//By default, since you want the button to NOT appear for all incoming traffic EXCEPT
//that which came from Home.aspx, the button's Visible property is set to false.
<asp:Button ID="btnRCA" runat="server" onclick="Button1_Click"
Text="Assign RCA" Width="147px" Visible="false" />
RCA.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
//If the querystring has a parameter called ShowButton and it's equal to "1",
//then set the button to Visible = true.
//Else, do nothing, keeping the button in it's default, Visible=false state.
//By putting this in an "IsPostback == false" check, you can guarantee that this will
//only happen on first page_load, and won't be triggered again even if you do other
//actions in the page that cause Postback
//For example, if you don't use this !IsPostback check, and you end up creating some
//new function that causes the button to be hidden again, but then you make a
//selection from a dropdown list that causes postback, you will trigger the call to
//make the button Visible again, even though that's probably what you don't want at
//this point, since your other new function set it to Visible = false.
if (!IsPostback)
{
if (Request.QueryString["ShowButton"] == "1")
{
RCAbtn.Visible = true;
}
if (Request.QueryString["Post_ID"] != null)
{
//do whatever you need to with the post ID
}
}
}
SomeOtherPage.aspx.cs
Response.Redirect("RCA.aspx?Post_ID=1234"); //button will be invisible
And then let's say later that you want to re-direct from some other page and have the button be visible, like the redirect from Home:
Response.Redirect("RCA.aspx?Post_ID=1234&ShowButton=1"); //button will be visible
If you don't like cluttering up your URL or you feel that it looks tacky to have what you are doing so plainly available to the user's eyes, you don't necessarily need to use "ShowButton". You could say ?Post_ID=1234&fkai3jfkjhsadf=1, and then check your query string for "fkai3jfkjhsadf". I like to do that sometimes because then from the users point of view, it makes me look like I'm doing something really technical and encrypted, and not just passing around a bunch of basic instructions in plain English :) Downside there is you need keep track of your own query string parameters.
Edit:
If you want to get the URL with only the Post_ID and nothing else, you can do this:
string currenturl = Request.Url.ToString(); //get the current URL
string urlToSend = currenturl.Substring(0, currenturl.IndexOf("?")); //cut off the QueryString entirely
urlToSend += "?Post_ID=" + Request.QueryString["Post_ID"]; //re-append the Post_ID
Be aware that your call to Substring will cause an exception if the URL doesn't have a QueryString, so please patch that up in whatever way works best for you (try/catch, etc.).
After that, you should just be able to use the "urlToSend" string in your mailMessage.Body.

on your second page in your page_load, try this:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Post_ID"] != null)
{
btnRca.Visible = true;
}
}
I don't know how you want to handle the visibility of this button in other cases, but this should answer your particular question.

Related

ASP.Net FormsAuthentication Rememberme

I am using forms authentication in a web application using the built-in Login capabilities, and it has been working well.
I would like to set DisplayRememberMe.visible to false depending on certain conditions (e.g. which Server, ip address, etc). Of course I can manually add visible="false" to the markup shown here, but that seems like a poor way to go.
<asp:CheckBox ID="RememberMe" runat="server" />
<asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="RememberMe"
CssClass="inline" >Keep me logged in</asp:Label>
Also, I can't figure out which asp field has the DisplayRememberMe field.
But more importantly, in the code behind file, I have added LoginUser.DisplayRememberMe = False, but it is ignored, and the label and checkbox are still visible. I have tried adding it to various events like Page.Load, Page.Init, Login_User.Init, Login_User.Prerender, but the checkbox and label are still visible after the page loads.
Am I using the proper call? Where should I place it to be effective?
This is my first post on SO, so please excuse any poor etiquette.
You can change visibility of CheckBox and Label by creating event of login control as
OnLoad="LoginUser_OnLoad"
On .cs page
protected void LoginUser_OnLoad(object sender, EventArgs eventArgs)
{
var login = (System.Web.UI.WebControls.Login)sender;
var checkbox = login.FindControl("RememberMe");
checkbox.Visible = false;
var label = login.FindControl("RememberMeLabel");
label.Visible = false;
}
You can also put your visibility conditions in LoginUser_OnLoad method.

Set value of variable upon link click

I currently have a listview on an ASP.NET webpage that displays "cottage" records from an Access database. The name of each cottage is displayed as a hyperlink so when clicked brings you to another webpage:
<li style="">Name:
<asp:Hyperlink ID="Cottage_NameLabel" NavigateURL="~/Cottage.aspx"
runat="server" Text='<%# Eval("Cottage_Name") %>' />
<br />
This works perfectly fine when selecting a hyperlink. What I want the system to do is to set the value of a publically declared variable (set in a module) to the Cottage_Name of the selected hyperlink. So say if i clicked on a hyperlink that said "cottage1", the public variable is set to "cottage1" and then the navigate URL opens the next webpage.
Would really appreciate it if anyone could help me do this!
Just use a LinkButton instead of a Hyperlink... Catch the click event and do whatever you want...
For instance:
<asp:LinkButton ID="Cottage_NameLabel" runat="server" Text="whatever" onclick="Cottage_NameLabel_Click" />
Then in CodeBehind:
protected void Cottage_NameLabel_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
Session["MyCottageName"] = btn.Text;
Response.Redirect("Cottage.aspx");
}
In your Cottage.Aspx page you can check the value of the Session variable like this:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["MyCottageName"] != null)
{
string name = (String)Session["MyCottageName"];
...
}
You can pass the name as a querystring variable to the page. If you go this route, you need to make sure you URL encode the cottage name:
<a href='/Cottage.aspx?name=<%# Server.UrlEncode(DataBinder.Eval(Container.DataItem, "Cottage_Name")) %>'><%# Eval("Cottage_Name") %></a>
And then on cottage.aspx you can get the cottage name:
Dim cottageName As String = Request.QueryString("name")
This would be preferable to a button or other postback solution as it removes the need for a postback and then a redirect.

ASP:Net LinkButton control Postback issue

I have an asp.net linkButton (or imageButton) control in my profile.aspx page. I'am checking Request.Querystring("id") in the page below in the code behind.
http: //localhost:42932/profile.aspx?id=1
When I first load the profile page it is not posted back. It is ok!. When I go to another users profile (the same page just the query string is different) using imageButton control with the adddress;
http: //localhost:42932/profile.aspx?id=2
it is posted back. I dont want it to be posted back. But if I go to this page with a regular html input element like
a href = "http: //localhost:42932/profile.aspx?id=2"
it is not posted back. So I want the image button behave like an html input element.
Here is my imageButton;
ASPX:
<asp:ImageButton ID="imgProfile" ImageUrl="images/site/profile1.png" runat="server"/>
.CS
imgProfile.PostBackUrl = "profile.aspx?id=" + Session["userID"];
Edit:
if (!IsPostBack)
{
Session["order"] = 0;
}
This control is in the page load. So it should be !postback with state I mentioned above. Because all the other functions are working when Session["order"] = 0
Make use of OnCLientClick instead of OnClick, so that you only run client side code. Then, sepcify that you return false;
i.e.
<asp:ImageButton ID="imgProfile" ImageUrl="images/site/profile1.png" runat="server" OnClientClick="return false;" />
But, why use a server control, when this can be done with a normal <img .. html control?
Rather than specifying a PostBackUrl I would recommend using Response.Redirect() in the button click event handler:
public void imgProfile_Click(object sender, eventArgs e){
Response.Redirect("profile.aspx?id=" + Session["userID"]);
}
Or alternatively, just use a Hyperlink control and set the NavigateUrl property during Page_Load:
<asp:HyperLink ID="imgProfile" runat="server"><img src="images/site/profile1.png" /></asp:Hyperlink>
imgProfile.NavigateUrl = "profile.aspx?id=" + Session["userID"];

UpdatePanel resetting object to inital state

I have an application that I am currently writing that works by iterating through nodes, and then updating the page with the information of the current node. I have an UpdatePanel in the page which contains a label, textbox, and a button. The label lists the currently available children of the current node, the user enters in which child they want to go to into the textbox, and then hits the submit button. I set the new value of the node in the submit button's event handler.
Here's my problem: Every time I enter in which node I want to navigate to, the object resets its value to the value it was initially initialized to. I have even put this same code into a Windows Form to validate that it's working correctly to iterate through my tree, and it works as it should, so I know my problem is AJAX-related.
This is the first app that I have written using AJAX, so I am still in the process of learning how it works. Any help would be greatly appreciated. I have Googled and searched SO through and through.
Here is the HTML:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="question" runat="server" Text=""></asp:Label>
<br />
<asp:TextBox ID="answer" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Submit" runat="server" Text="Submit" onclick="Submit_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
And the C#:
protected void Submit_Click(object sender, EventArgs e)
{
int ans = int.Parse(answer.Text);
if (!current.ChildIDs.Contains(ans))
{
return;
}
current = tree.Node(ans);
question.Text = current.Question;
}
current is the current node, which has a public ArrayList of all of its children's IDs. tree is the NodeTree I have; calling Node just returns the new node. Both current and Tree get initialized in the Page_Load event, and that only fires once (when the page is first loaded).
It's really pretty simply code; I'm just having difficulty understanding why the AJAX isn't working correctly.
I have even put this same code into a
Windows Form to validate that it's
working correctly to iterate through
my tree, and it works as it should, so
I know my problem is AJAX-related.
It sounds like you're expecting ASP.NET to remember what the object current is between requests, since that's how Windows forms applications work.
Web applications are stateless - after each request, ASP.NET discards all your variables. To access the variable during a subsequent request, you have to either:
1) Send enough data with the request to reconstruct the variable. You can do this using a querystring parameter or an HTML form value (the hidden fields another response mentioned).
2) Save the variables in a Session store (which can be in-memory or backed by a database).
3) Store the value in a coookie.
Of these three, it's easiest to show you how to use Session, given what you've shared in your question. However, beware: session has its risks - by default, ASP.NET session objects are stored in-memory, and it's a potential security hazard. But here's how you should be able to get your application to work.
// In your Page_Load code that initializes your 'current' variable
// When the user first requests the page, create a new Node
if (! this.IsPostBack)
{
Node current = new Node(); //
Session("currentNode") = current;
}
// When the user clicks a button on the page (posts), use the
// node in session instead
else
{
current = Session("currentNode");
}
When you update non-form elements in the browser (labels, literals, etc.), .NET is unable to see any of the changes you've made.
Try adding a hidden input for each label that records the new value. Then within the method you have wired up to the button's OnClick event, do something like this:
myLabel.Text = myHiddenInput.value;
I think you just need to tell the updatepanel to update itself. Try this:
protected void Submit_Click(object sender, EventArgs e)
{
int ans = int.Parse(answer.Text);
if (!current.ChildIDs.Contains(ans))
{
return;
}
current = tree.Node(ans);
question.Text = current.Question;
UpdatePanel.Update();
}

Repeater databound loses data & event on postback - is there a best practice solution?

Currently struggling with a problem that I've encountered variations on in the past. At the moment a worthwhile solution escapes me, but it seems such an obvious issue that I can't help wondering whether or not there's a "best practice" approach I should adopt.
Without code, here's the issues in a nutshell:
page has databound control (a repeater) which isn't populated until user inputs data and clicks a button.
Repeater item template contains a button
User clicks button, page posts back. On load, the repeater is actually empty so event is never handled because the originating control no longer exists
Go back to the beginning of wretched cycle
I've confirmed that this is the problem because if you provide the repeater with some static data on page load, everything works fine. But of course that's no use because it has to be populated dynamically.
Is there a commonly approved way round this headache? I can store the data in session and re-use it on page load, but it seems terribly clumsy.
Cheers,
Matt
If the event is being fired by a button within a repeater then this would bubble up to the repeaters ItemCommand event. Using a buttons CommandName and CommandArgument parameters you can then identify which button was clicked and act accordingly. Below is some basic markup and code behind to demonstrate the approach:
HTML:
<asp:Repeater ID="rptTest" runat="server" onitemcommand="rptTest_ItemCommand"
onitemdatabound="rptTest_ItemDataBound">
<ItemTemplate>
<p>
<asp:Button ID="btnTest" runat="server" />
</p>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnLoad" runat="server" Text="Load" onclick="btnLoad_Click" />
Code behind events:
protected void rptTest_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Button button = (Button)e.Item.FindControl("btnTest");
button.Text = string.Format("Button {0}", e.Item.DataItem.ToString());
button.CommandName = e.Item.ItemIndex.ToString();
}
protected void rptTest_ItemCommand(object source, RepeaterCommandEventArgs e)
{
Response.Write(string.Format("Postback from button {0}", e.CommandName));
}
protected void btnLoad_Click(object sender, EventArgs e)
{
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
rptTest.DataSource = list;
rptTest.DataBind();
}
Hopefully i've understood the problem and this helps.
If any of your controls are created dynamically, then they have to be recreated during post back in order for the events etc to get hooked back up.
If this is the case, take a look at a control built by a guy named Denis Bauer. We use this with just some slight modifications and it's perfect.

Resources