I'm having some trouble with my main menu on my ASP.NET website. What I want is, when a user clicks on a link, it should change it's color to black and remain black until the user clicks on the other links.
In other words: I want to highlight the selected link.
So far I've got it working using some workaround JavaScript (should consider using jQuery instead I think), but the problem is, that the style dosn't remain on page postback (or so it seems..)
My current javascript:
<script type="text/javascript">
var last = "none";
function LinkSelector(link) {
if (last != "none") {
document.getElementById(last).className = "NormalLink";
}
document.getElementById(link).className = "ActiveLink";
last = link;
}
</script>
As I wrote, it sure changes the class name when clicked, but dosn't remain that way when the new page is loaded.
Anyone got a workaround on this? :)
Thanks in advance.
All the best,
Bo
Typically, I'll use the ASP:Menu control. It provides a decent amount of control over the menu items in it.
For example, here's a generic method that I dump in a masterpage and run during the initial page hit. This method loops over the menu items in the menu control, and selects the menu item that corresponds to the current URL.
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
SelectMenuItem();
}
}
private void SelectMenuItem() {
string rawurl = Request.RawUrl.ToLower();
rawurl = rawurl.Substring(rawurl.LastIndexOf("/") + 1);
if (rawurl.IndexOf("?") >= 0)
rawurl = rawurl.Substring(0, rawurl.IndexOf("?"));
foreach (MenuItem mi in mnuMain.Items) {
if (mi.ChildItems.Count == 0) {
if (mi.Value == rawurl) {
mi.Selected = true;
break;
}
}
else {
foreach (MenuItem cmi in mi.ChildItems) {
if (cmi.Value == rawurl) {
mi.Selected = true;
break;
}
}
if (mi.Selected)
break;
}
}
}
Here are a few of the menu items I have in my asp menu control. Note that I use the Value attribute to help me indicate which menu item pertains to the requested URL in the method above.
<Items>
<asp:MenuItem Text="Forms" Value="authorization">
<asp:MenuItem Text="New Authorization Form" Value="createauthform.aspx" NavigateUrl="~/CreateAuthForm.aspx"></asp:MenuItem>
<asp:MenuItem Text="Manage My Authorization Forms" Value="myrequests.aspx" NavigateUrl="~/MyRequests.aspx"></asp:MenuItem>
<asp:MenuItem Text="Audit Attendance Form" Value="auditform.aspx" NavigateUrl="~/AuditForm.aspx"></asp:MenuItem>
<asp:MenuItem Text="Tax Determination Statement" Value="taxstatement.aspx" NavigateUrl="~/TaxStatement.aspx"></asp:MenuItem>
</asp:MenuItem>
</Items>
Consider implementing your "last" variable as a static member of your function, here's how it's done. That way its value will be retained between function calls. I am not sure if it's retained between page loads, but you can test it.
If not, you'll have to somehow instruct ASP to remember the value. Regarding that, I'm as useful as a lump weight.
Related
I have this aspx script for the button for pop-up:
<asp:Button ID="btnNewEntry" Text="Post Code Search" OnClick="btnNewEntry_Click" runat="Server" target="_blank"/>
and behind:
protected void btnNewEntry_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.Page.GetType(), "", "window.open('../search/postcode_search/Default.aspx?code="+ p +"','Post Code Search','width=800,height=300,left=100,top=100,resizable=yes'); popup_handle.focus();", true);
}
But as the button is clicked the pop-up is opened but the parent page is refreshed. Why it's so? any work around?
Page got refreshed when a request to server is made, and server controls like Button has a property AutoPostback = true by default which means whenever they are clicked a trip to server will be made. Set AutoPostback = false for insert button, and this will do the trick for you.
or
Add OnClientClick="return false;" ,
<asp:button ID="btninsert" runat="server" text="Button" OnClientClick="return false;" />
Perhaps a little explanation of what is actually happening with your code will help. We have already discussed the auto postback, so you know that clicking that button will send the event back to the server. The page initializes again and reloads the view state and all of the posted data. After that, the button click event is handled.
At this point, your code writes the window.open script to the page. Keep in mind this is no where specific. This is just script that is added some where on the page and executed. The view state then gets updated and the page is sent back to the client. If the user reloads the page, that script is going to execute again.
Your best bet is going to be converting that to a client side button only. Find a way to get the necessary data back from the server before loading your popup. The easiest way to do that is make an AJAX call and open your pop up on success from your end point.
Try this.Updated one.
<asp:Button ID="btnNewEntry" Text="Post Code Search" OnClick="btnNewEntry_Click" runat="Server" target="_blank"
OnClientClick="javascript:window.open('../search/postcode_search/Default.aspx?code=+ p','Post Code Search','width=800,height=300,left=100,top=100,resizable=yes').focus();return false;"/>
Issue was due to "+ p +".
So as advised, i decided to go to client side. Here is my script:
<button onclick="OpenPopup()" type="button">Post Code Search</button>
and javascript code above it:
<script>
function OpenPopup() {
var getQueryString = function ( field, url ) {
var href = url ? url : window.location.href;
var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
var string = reg.exec(href);
return string ? string[1] : null;
};
var str = getQueryString('code');
if (str != null) {
p = str.replace(/%20/g, ' ');
}
else {
p = "";
}
var url = "../search/postcode_search/Default.aspx?code=" + p;
window.open(url, "Post Code Search", "toolbar=no, location=no,status=yes,menubar=no,scrollbars=yes,resizable=no, width=750,height=400,left=430,top=100");
return false;
}
</script>
so basically what it does, it grabs parameter from parent window url and adds to popup window url. My parent window url:
/Customer.aspx?code=V6E%20111&firstname=MyName
I hope it helps for others as well. Thanks for help guys.
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.
I have a Search feature. if the search string is empty and user clicks "GO" then the postback of the gridview shouldn't happen and the alert (as mentioned in below code) should get fired up.
My gridview is in update panel. Below is the logic that i have written but it doesn't works.
protected void btnGo_Click(object sender, EventArgs e)
{
if (!txtSearchString.Text.Equals(string.Empty))
{
BinGrid();
upnl1.update //update panel is updated here.
}
else
{
ScriptManager.RegisterStartupScript(this.upnl1, this.GetType(), "Search", "alert('Enter search text');", false);
//upnlgvOpportinities.Update();
//upnlAdmin.Update();
return;
}
}
Please help! Let me know if any info is needed
This logic is wrong. It should do using javascript if you want to avoid the postback at first place.
Have your javascript return false when textbox is empty and true when not
<asp:button runat="server".... OnClientClick="return myfunction(); " />
You can check if textbox is empty or not in myfunction()
Replace Your ScriptManager line with below code line.
ScriptManager.RegisterStartupScript(this.upnl1, this.GetType(), "Script", "alert('Enter search text');", true);
If you don't want a request to the server to be sent (if I understood your needs right), than you need a client-side solution, that is handle button click with javascript and conditionally prevent the postback. However your current code is server-side, and is executed on a server after the postback has occurred.
As to client-side, here is one possible way. Define a js function that simply checks the value of the search box and returns false if it is empty. On the button click simply call this function. If a click handler returns false, further processing of the button click will be stopped and the postback won't occur:
function checkSearch() {
var searchBox = document.getElementById('HereComesSearchBoxClientID');
if (searchBox.value == '') {
alert('Enter search text');
return false;
} else {
return true;
}
}
<asp:Button ID="SearchButton" runat="server" Text="GO" OnClick="ServerSideHandler" OnClientClick="checkSearch();" />
#Madhur Ahuja's way is the correct one. Expanding that a little bit more.
HTML
<asp:Button ID="txtSearchString" runat="server"
OnClientClick="javascript:return CheckifEmpty(this);" />
Javascript
function CheckifEmpty(objSearchBox) {
//always trim, otherwise it will accept a string of spaces
var isEmpty = objSearchBox.value.trim() == "";
if (isEmpty) {
alert('Enter search text');
}
return !isEmpty;
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
};
}
I have an AjaxToolkit TabContainer control with a number TabPanels. Each TabPanel has a different UserControl in it to display some information. Some of these UserControls have either a LinkButton or a GridView with a command button in them. The TabContainer has AutoPostBack="false" and this is how I would like to keep it.
When you click on the LinkButton or command button in the GridView the expected events fire and the code runs. But when the page is returned the initial tab is selected again (and not the tab the user was previously viewing).
So my question is: Is there a way to maintain the selected tab when some child control causes a postback?
Some constraints:
I do not way to turn AutoPostBack on. This means the linked solution for this question question is no good in this case.
The UserControls are not always used in a TabContainer/TabPanel so the solution can not assume that this is the case.
The solution needs to be fairly robust and straightforward as there could be different devs working on this code.
I solved this problem by creating my own control that inherits from TabContainer, then overriding LoadClientState() like this:
protected override void LoadClientState(string clientState)
{
base.LoadClientState(clientState);
// If post back was caused by control on a tab, make that tab the active one
if (!string.IsNullOrEmpty(this.Page.Request.Params["__EVENTTARGET"]))
{
foreach (string ctlName in this.Page.Request.Params["__EVENTTARGET"].Split('$'))
{
if (this.FindControl(ctlName) is TabPanel && this.Tabs.Contains(this.FindControl(ctlName) as TabPanel))
{
this.ActiveTab = (this.FindControl(ctlName) as TabPanel);
break;
}
}
}
}
This finds the TabPanel on which the control causing the postback resides, then makes that the active panel.
I got this from another forum. You set this in the pageload. I don't know if that would help with them being set to AutoPostBack=false, but if you haven't given up on it yet, I hope this helps
if (ViewState("ActiveTabIdx") != null)
{
activeTabIndex = Convert.ToInt32(ViewState("ActiveTabIdx"))
if (activeTabIndex != null)
{
TabContainer1.ActiveTabIndex = activeTabIndex;
}
}
you need to add ActiveTabChanged event for tab container and you can keep active tab index in view state, and on page load just check if it is not null then set it as Active tab index.
protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
{
ViewState["ActiveTabIndex"] = TabContainer1.ActiveTabIndex;
}
PageOnLoad Event code
if (!(ViewState["ActiveTabIndex"] == null) )
{
TabContainer1.ActiveTabIndex = (int)ViewState["ActiveTabIndex"];
}
Make sure to add following attributes in TabContainer tag
AutoPostBack="true" OnActiveTabChanged="TabContainer1_ActiveTabChanged"
I am using JScript in ASP.NET 2005. I have a page with a checkbox and a dropdown list. When the checkbox is checked, the dropdown is to be disabled. During Postback of the page, this behavior should be retained. I am using a javascript function as follows
if((chkOwner[1].checked==true))
{
document.getElementById(ddlClientID).disabled=true;
document.getElementById(ddlClientID).className = "form-disabled";
document.getElementById(ddlClientID).selectedIndex = 0;
}
else
{
document.getElementById(ddlClientID).disabled=false;
document.getElementById(ddlClientID).className = "form-input";
document.getElementById(ddlClientID).selectedIndex = 0;
}
This works, almost. However, the dropdown selection is not retained after postback (when checkbox is not selected). [It goes to zero index's value]
Apprently the solution is to remove the last line, i.e, in the else part, remove the selectedIndex =0 .
But, when I do that the disabling of dropdown (when check box is checked) is not working after post back.
Could you please help me on this?
More Info: I am using ClientScript.RegisterStartupScript for checking this at each page load.
Thanks
Lijo
--CODE-----
Following is what I am trying. (This is a sample application I created just now. It does not work. This can only show what I am trying to achieve.)
function ManageInputsFor()
{
if((document.getElementById(chbx).checked==true))
{
document.getElementById(ddlClientID).disabled=true;
document.getElementById(ddlClientID).className = "form-disabled";
document.getElementById(ddlClientID).selectedIndex = 0;
}
else
{
document.getElementById(ddlClientID).disabled=false;
document.getElementById(ddlClientID).className = "form-input";
document.getElementById(ddlClientID).selectedIndex = 0;
}
}
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(Page.GetType(), "chbx", #"<script language=""javascript"" type=""text/javascript"">var chbx ='" + CheckBox1.ClientID + "'</script>");
ClientScript.RegisterClientScriptBlock(Page.GetType(), "ddl", #"<script language=""javascript"" type=""text/javascript"">var ddlClientID ='" + DropDownList1.ClientID + "'</script>");
ClientScript.RegisterStartupScript(Page.GetType(), "onLoadCallForManageInputs", #"<script language=""javascript"" type=""text/javascript"">ManageInputsFor();</script>");
CheckBox1.Attributes.Add("onclick", "ManageInputsFor();");
}
you'll have to do a server side evaluation of the checkbox during the pastback, and set the dropdownlist enabled or not. the disabled attribute of the drop down isn't sent to the server during the post operation (neither is the value of the control when it's disabled,btw).
edit: to retain the value in the drop down across a postback, you can copy the selected value to another control which will be posted back, and then assign the value back to the drop down during server processing.
Basically, your problem is happening bc when you use javascript to change the state of an ASP control, that stat is not posted back to the server. You have to figure out a way to send it. Using a hidden control, or adding a parameter to the querystring are two such methods.