check the url of current page in if statement - c#

so i have this button that appears on multiple pages all leading to the parent page. But now - when i reach the parent page i still have the button showing. I want to remove/hide the button when on the parent page.
Is it possible that i could check my current page url and check to see if it the parent page?
<a id="element" href="/Pages/#ViewBag.ElementId" class="btn">
<i>Home</i>
</a>
thinking using an if statement surrounding the tag

If you wanted to do your check in the code behind page, you can always execute the code below during the page load event.
if (Path.GetFileName(Request.Url.LocalPath) == "ParentPage.aspx")
{ element.visible = false; }
else
{ element.visible = true; }

yeah that's what the window.location variable is for see this

When you are in your parent page, what is the ElementId value ?
I assume it can be null, so you may be able to check this value before displaying your button
#if(ViewBag.ElementId != null){
<a id="element" href="/Pages/#ViewBag.ElementId" class="btn">
<i>Home</i>
</a>
}
else { //TODO...
}

It looks like ASP.NET MVC to me.
#if (!Request.Url.AbsolutePath.EndsWith("/i/dont/want/this"))
{
<a id="element" href="/Pages/#ViewBag.ElementId" class="btn">
<i>Home</i>
</a>
}

Related

Programmatically click button in C#

I'm trying to programmatically click a series of buttons on an HTML web page which looks as follows:
<div class="srp-actions blue-button"><a class="primary-action-button label" href="/people/invite?from=profile&key=243930744&firstName=Will&lastName=Yang&authToken=p8Oz&authType=OUT_OF_NETWORK&connectionParam=member_desktop_search_people-vertical-module&csrfToken=ajax%3A7824954558998584370&trk=vsrp_people_res_pri_act&trkInfo=VSRPsearchId%3A12487701484818103943%2CVSRPtargetId%3A243930744%2CVSRPcmpt%3Aprimary" data-li-result-interaction="instant-connect" data-li-success-text="Invite Sent" data-li-connect-href="/people/contacts-search-invite-submit?memIds=243930744&authTokens=p8Oz&authTypes=OUT_OF_NETWORK&from=voltron&firstName=Will&lastName=Yang&isAjax=true&connectionParam=member_desktop_search_people-vertical-module&csrfToken=ajax%3A7824954558998584370&trk=vsrp_people_res_invite_act&trkInfo=VSRPsearchId%3A12487701484818103943%2CVSRPtargetId%3A243930744%2CVSRPcmpt%3Aprimary">Connect</a><div class="secondary-actions-trigger"><button role="button" class="trigger"><span>Secondary Actions</span></button><ul class="menu"><li>Send InMail</li><li>Share</li></ul></div></div>
Here's the current code to find the button element and perform the action:
HtmlElementCollection elements = webBrowser1.Document.GetElementsByTagName("a");
// First find and click "Connect" buttons
foreach (HtmlElement item in elements)
{
if (item.OuterHtml.Contains("action-button label") &&
!item.OuterHtml.Contains("Message") &&
item.OuterHtml.Contains("OUT_OF_NETWORK"))
{
item.SetAttribute("href", item.GetAttribute("data-li-connect-href"));
item.InvokeMember("Click");
}
}
The code properly find the anchor element, but the InvokeMember method doesn't seem to yield any result, any idea what is wrong?
The tag you are using does not specify exactly which specific tag you need:
x = webBrowser1.Document.GetElementsByTagName("a")
Instead try :
x= webBrowser1.Document.GetElementsById("anchor_id");
x.InvokeMember("click");
Or try using following method to verify whether its the intended tag you're using via attribute.
if (element.GetAttribute(attribute).Equals(attName))

How getAttribute("onclick")

For example I have this html code:
<a href="#" onclick="return Index.submit_login('server_pl80');">
<span class="world_button_active">Świat 80</span>
</a>
And I need to get attribute of onclick, because I may get more links and I must find difference between them. For my opinion get attribute of onclick is only one way.
But if I GetAttribute("onclick") from HTMLElement it will return System.__ComObject.
Is there any idea how read onclick value from webBrowser?
I have only this:
HtmlElement selected_div = #webBrowser1.Document.GetElementById("div_id").GetElementsByTagName("div")[0];
HtmlElement a = selected_div.GetElementsByTagName("a")[0];
string rightLink = a.GetAttribute("href");
string onclickLink = a.GetAttribute("onclick"); // return "System.__ComObject" string
if (rightLink == "http://www.example.com/#")
a.InvokeMember("click", null);
"onclick" or "onClick" in getAttribute(); doesn't make a difference
This code works but click on first link on the list of servers.. I need choose the server and links have difference only in onclick attribute.

C# - Sending value to HREF in html

I have written a project in C# in which I load a HTML webpage if an event occurs during teh course of the project usage.
My issue is that inside my html page, I have a href node inside a tag as such:
<a href="http://pseudo01.hddn.com/vod/demo.flowplayervod/flowplayer-700.flv"
style="display:block;width:inherit;height:inherit;background-color: black;overflow:hidden"
id="player">
</a>
I would like to change the href value programatically by sending a C# variable (called myHrefFile) depending on what the user did.
How can this be done?
you can do something like this
<a href="<%= someMethodThatGetHrefValue() %>"
style="display:block; width:inherit;height:inherit; background-color:black;
overflow:hidden"
id="player">click</a>
call the method that decide what should be href for link .
and put all the logic of deciding href in that method like this
public string someMethodThatGetHrefValue()
{
if(someval == true)
return "http://www.google.com";
else
return "http://www.yahoo.com";
}
Something like this perhaps? This is an Asp.net solution.
<asp:LinkButton ID="LinkBut" runat="server" onclick="LinkBut_Click">Click here</asp:LinkButton></p>
protected void LinkBut_Click(object sender, eventArgs e)
{
string myHrefFile = "";
if(Value.equals(true))
{
myHrefFile = "page1.aspx";
}
else
{
myHrefFile = "page2.aspx";
}
Response.Redirect(myHrefFile );
}

Get variable & keep changes after postback

This question is related to: Hide div on clientside click
The issue I am having is that after postback event from asp.net happens onClick any clientside changes made reset how can I keep the client side changes I am making.
Second question how can I get a variable from code behind and pass it into my javascript to perform a comparison.
Html:
<div runat="server" id="someDiv1" enableviewstate="true" >
<asp:LinkButton OnClientClick="Show_Hide_Display()"
ID="lbtnDiv1"
runat="server"
CausesValidation="true"
OnClick="lbtn_onClickServer">
</asp:LinkButton>
</div>
<div runat="server" class="tick" id="div2" style="display:none;" enableviewstate="true">
</div>
Javascript:
<script type="text/javascript">
function Show_Hide_Display() {
var div1 = document.getElementById("<%=someDiv1.ClientID%>");
var div2 = document.getElementById("<%=div2.ClientID %>");
if (div1.style.display == "" || div1.style.display == "block") {
div1.style.display = "none";
div2.style.display = "block";
}
else {
div1.style.display = "block";
div2.style.display = "none";
}
}
</script>
The OnClick event causes a postback like it should, on this occassion it checks if users, chosen username is available.
If it is available show a tick, if it isn't error.
I got the error working and am trying to program the tick on client side.
So OnClientClick I am able to toggle between some text and a tick. So I need to:
Get the bool result from code behind
After postback keep tick (if username is available)
I am almost there but can't quite figure the last two points out.
If you are using an UpdatePanel in your page, and assuming that div which you are trying to toggle is outside the control, you can always inject javascript on a partial postback:
Like for e.g. on your button's click event which executes on a partial postback make a call to ScriptManager.RegisterClientScriptBlock() --> How to retain script block on a partial postback?
Alternatively, you can append an end request handler. This is some javascript which should run after the partial postback. --> ASP.NET Register Script After Partial Page Postback (UpdatePanel)
The answer for the both questions lies of checking the boolean value send from the code behind.
1-----.in code-behind c#
protected void Page_Load(object sender, System.EventArgs e)
{
var linkbtn = (Button)Page.FindControl("lbtnDiv1");
linkbtn .Attributes.Add("onClick", "Show_Hide_Display('" + parameter+ "')");
}
2------- change your javascript
function Show_Hide_Display(parameter)
{
if( paramater=='true')
{
----your logic---
}
else
{
----your logic
}
}

C# - How to change HTML elements attributes

My master page contains a list as shown here. What I'd like to do though, is add the "class=active" attribute to the list li thats currently active but I have no idea how to do this. I know that the code goes in the aspx page's page_load event, but no idea how to access the li I need to add the attribute. Please enlighten me. Many thanks.
<div id="menu">
<ul id="nav">
<li class="forcePadding"><img src="css/site-style-images/menu_corner_right.jpg" /></li>
<li id="screenshots">Screenshots</li>
<li id="future">Future</li>
<li id="news">News</li>
<li id="download">Download</li>
<li id="home">Home</li>
<li class="forcePadding"><img src="css/site-style-images/menu_corner_left.jpg" /></li>
</ul>
</div>
In order to access these controls from the server-side, you need to make them runat="server"
<ul id="nav" runat="server">
<li class="forcePadding"><img src="css/site-style-images/menu_corner_right.jpg" /></li>
<li id="screenshots">Screenshots</li>
<li id="future">Future</li>
<li id="news">News</li>
<li id="download">Download</li>
<li id="home">Home</li>
<li class="forcePadding"><img src="css/site-style-images/menu_corner_left.jpg" /></li>
</ul>
in the code-behind:
foreach(Control ctrl in nav.controls)
{
if(!ctrl is HtmlAnchor)
{
string url = ((HtmlAnchor)ctrl).Href;
if(url == GetCurrentPage()) // <-- you'd need to write that
ctrl.Parent.Attributes.Add("class", "active");
}
}
The code below can be used to find a named control anywhere within the control hierarchy:
public static Control FindControlRecursive(Control rootControl, string id)
{
if (rootControl != null)
{
if (rootControl.ID == id)
{
return rootControl;
}
for (int i = 0; i < rootControl.Controls.Count; i++)
{
Control child;
if ((child = FindControlRecursive(rootControl.Controls[i], id)) != null)
{
return child;
}
}
}
return null;
}
So you could do something like:
Control foundControl= FindControlRecursive(Page.Master, "theIdOfTheControlYouWantToFind");
((HtmlControl)foundControl).Attributes.Add("class", "active");
Forgot to mention previously, that you do need runat="server" on any control you want to be able to find in this way =)
Add runat="server" on the li tags in the masterpage then add this to the appropriate page_load event to add the 'active' class to the li in the masterpage
HtmlGenericControl li = HtmlGenericControl)Page.Master.FindControl("screenshots");
li.Attributes.Add("class", "active");
You could register a client script like this:
(set id to the id of the li that you want to set to active)
ClientScript.RegisterStartupScript(this.GetType(), "setActiveLI", "document.getElementById(\""+id+"\").setAttribute(\"class\", \"active\");", true);
This generates a JavaScript call on the page near the bottom after elements have already been rendered.
All the parts have already been provided in previous answers, but to put the whole thing together, you'll need to:
add the runat="server" attribute to the <ul> and <li> elements
add a public method to do the work on the master page that can be called from the pages using the master page
call the method from the Page_Load of the pages
Alternatively you could also add the code to the OnLoad(...) method of the master page, so you don't have to add the method call to the Page_Load on every page.
If they were runat=server you could use the attributes property.
In order to find that particular control it will need to be defined as public (in the generated designer)
Or will need to be wrapped by a public get in the codebehind.
You can expose the li's on the master page to any content pages by wrapping them in properties on the master page:
public GenericHtmlControl Li1
{
get
{
return this.LiWhatever;
}
}
Then on the content page:
MasterPage2 asd = ((MasterPage2)Page.Master).Li1.Attributes.Add("class", "bla");
If i've got that right!
I found a link that works using CSS and involves only changing the body tag's class attribute. This means there's no Javascript and there's no for loops or anything.
#navbar a:hover,
.articles #navbar #articles a,
.topics #navbar #topics a,
.about #navbar #about a,
.contact #navbar #contact a,
.contribute #navbar #contribute a,
.feed #navbar #feed a {
background: url(/pix/navbarlinkbg.gif) top left repeat-x; color: #555;
}
....
<body class="articles" onload="">
<ul id="navbar">
<li id="articles">Articles</li>
<li id="topics">Topics</li>
<li id="about">About</li>
<li id="contact">Contact</li>
<li id="contribute">Contribute</li>
<li id="feed">Feed</li>
</ul>
Read more here
http://www.websiteoptimization.com/speed/tweak/current/
Try this
the great example for future use. i know this thread is old, but for future queries...
http://community.discountasp.net/showthread.php?p=33271
Thanks For the solution.
Mininized code.
Master page control can also find in the child page..
i mean master page contains html contol
and chilld page can find the master page html conrol like this
((HtmlControl)this.Master.FindControl("dpohome1")).Attributes.Add("class", "on");
Simple logic and minimal code, I usually use the following code, especially in dynamic menu. Hope this helps.
Create this method code in the code behind master page
CODE BEHIND (C#)
protected string SetCssClass(string page)
{
return Request.Url.AbsolutePath.ToLower().EndsWith(page.ToLower()) ? "active" : "";
}
In the menu list items you have created call this method passing the page name like this
HTML PAGE (ASPX inline code)
<li id="screenshots" class = "<%= SetCssClass("screenshots.aspx") %>">
Screenshots</li>
<li id="future" class = "<%= SetCssClass("future.aspx") %>">
Future</li>
and so on.
By this method, every time you add a page and link, you don't have to write code in every page. Just when you add the link in the master page, with every <li> invoke the SetCssClass(pagename) method call for setting class and it's done. (you can rename the method as per your ease.
You can use longer codes if you are being paid per lines of code bcoz then this is just one line of code. (lol). Just kidding. Hope it helps.
Note: I am ignoring other parts of the html code, you can include them also, that would work fine.

Categories

Resources