comparing the page's url to a's href - c#

i am trying to do that when the page's url equals the <a>'s href than it will change something's class.
it does changes the page on a click on the link, but it doesnt change the class of the <li>
here is what i have done:
html:
<div id='settingNev' >
<ul >
<li id="L1" runat="server"><a id="A1" href="../newsFeed/allEr.aspx" runat="server"><span>Er</span></a></li>
<li id="L2" runat="server"><a id="A2" href="../newsFeed/allEe.aspx" runat="server"><span>Ee</span></a></li>
</ul>
</div>
code behind:
if (A1.HRef.ToString() == Request.Url.ToString())
{
L1.Attributes.Add("class", "active");
}
if (A2.HRef.ToString() == Request.Url.ToString())
{
L2.Attributes.Add("class", "active");
}
the class active works, i have checked it.
by the way this code is on a master page connected to both pages in the <div id='settingNev' >.
Tnx for the help :D

The problme is A1.HRef returns relative url. On the other hands, Request.Url returns absolute url.
In order to fix it, you want to use server control for hyper link, and resolve it back to absolute path.
<ul>
<li id="L1" runat="server">
<asp:HyperLink runat="server" ID="A1HyperLink"
NavigateUrl="~/newsFeed/allEr.aspx">
<span>Er</span>
</asp:HyperLink>
</li>
</ul>
string url = Request.Url.PathAndQuery;
string a1 = ResolveUrl(A1HyperLink.NavigateUrl);
if (string.Equals(a1, url, StringComparison.InvariantCulture))
{
L1.Attributes.Add("class", "active");
}
Another method
Resolve A1's relative path to absolute path using ResolveUrl
<div id='settingNev' >
<ul >
<li id="L1" runat="server"><a id="A1"
href="../newsFeed/allEr.aspx"
runat="server"><span>Er</span></a></li>
</ul>
</div>
string url = Request.Url.PathAndQuery;
string a1 = ResolveUrl(A1.HRef);
if (string.Equals(a1, url, StringComparison.InvariantCulture))
{
L1.Attributes.Add("class", "active");
}

You need to convert the relative url to absolute in order to compare with the page url.
For some odd reason, I couldn't find any Url helper that supports parent paths in URL so the only workaround I can think of is using Server.MapPath() for this:
string pagePath = Server.MapPath(Request.FilePath);
Dictionary<HtmlAnchor, Label> anchorMapping = new Dictionary<HtmlAnchor, Label>();
anchorMapping.Add(A1, L1);
anchorMapping.Add(A2, L2);
foreach (HtmlAnchor currentAnchor in anchorMapping.Keys)
{
if (Server.MapPath(currentAnchor.HRef).Equals(pagePath))
{
anchorMapping[currentAnchor].Attributes.Add("class", "active");
break;
}
}

Related

Variable Not Recognized When Data Binding Attempted

Here is a snippet of my code:
<%for (int i = 1; i <= MessageList.Count; i++)
{
switch (LevelList[i-1])
{
case 0:%>
<div class="well offset1" style="width:80%">
<h1><%= MessageList[i - 1].Header%></h1>
<p><%= MessageList[i - 1].Body%></p>
<ul>
<li style="display:inline">Likes: <%= MessageList[i - 1].NumberOfLikes%></li>
<li style="display:inline">Replies: <%= MessageList[i - 1].NumberOfReplies%></li>
</ul>
<ul>
<li style="display:inline"><asp:Button ID="LikeButton" messID="<%# MessageList[i-1].MessageID %>" runat="server" Text="Like" /></li>
<li style="display:inline"><asp:Button ID="ReplyButton" messID="<%# MessageList[i-1].MessageID %>" runat="server" Text="Reply" /></li>
</ul>
</div>
<%break;
My problem is with the "messID" in this part:
<li style="display:inline"><asp:Button ID="LikeButton" messID="<%# MessageList[i-1].MessageID %>" runat="server" Text="Like" /></li>
At first I was attempting to pass a variable to the codebehind using messID="<%= calculated value%>" and using Button.Attribute["messID"] to access this variable, however, instead of passing the calculated variable as a string this passed a string that looked <%= calculated variable%>. After some research I found out that the <% could not be used with asp controls. So now I am attempting to use the <%# tag and DataBind(), however, now whatever is inside the <%# tags is not recognizing the variable i which is part of the forloop. Why does this happen?
Why not you just use html a tag?
All I want to do is to procedural generate buttons on my page, each of which will correspond to a message. When a user clicks on one of the reply buttons, it takes them to a page where they can write their response.
change
<li style="display:inline"><asp:Button ID="LikeButton" messID="<%# MessageList[i-1].MessageID %>" runat="server" Text="Like" /></li>
to
<li style="display:inline">Like</li>

Difference between an internal and external link

I have an image which when clicked, redirects to another page. I need a way to know whether the link is internal(page of the application) or an external link. If the link is external I would want it to pop up in a new tab and if it is internal pop up in the same tab.
This is the code section.
<a class="lnkImage" href="#item.ImageURL" target="_blank">
<img id="PrivateimgPreview" src="#item.ActualImage" />
</a>
ImageURL and Actual image are coming from the model. Basically I want this functionality.
if(External)
{
<a class="lnkImage" href="#item.ImageURL" target="_blank">
<img id="PrivateimgPreview" src="#item.ActualImage" />
</a>
}
else if(internal)
{
<a class="lnkImage" href="#item.ImageURL">
<img id="PrivateimgPreview" src="#item.ActualImage" />
</a>
}
I am aware that by using Request.Url.Host I can get the host and compare it, but that would mean hard coding it and will have to be changed in different hosts. Is there a way to generically find out the domain of #item.ImageURL in the view?
UPDATE: I can do the Request.URL for both the domain of the website I am and the domain of the #item.ImageURL in the controller and set a boolean in my model, but I have 4 such sections. One link for the image, one for the image header, one for the image details and so on. So this will have me introduce 4 new model objects, set each one of them in the controller. So i want it to be possible to compare it in the view.
Please review this one.
It compares href with window.location.origin using indexOf. If it is found, it changes the window.location = href, if not it triggers anchor.click()
var ls = Array.from(document.querySelectorAll(".lnkImage img"));
ls.forEach(function(l) {
l.addEventListener('click', function(e) {
var ori = window.location.origin;
var hr = this.parentNode.href;
if (hr.indexOf(ori) >= 0) {
window.location = hr;
console.log('internal');
} else {
this.parentNode.click();
console.log('external');
}
})
})
<!--internal-->
<a class="lnkImage" href="http://stacksnippets.net" target="_blank">
<img id="PrivateimgPreview" src="#item.ActualImage" />
</a>
<!--external-->
<a class="lnkImage" href="http://othersite.com/test" target="_blank">
<img id="PrivateimgPreview" src="#item.ActualImage" />
</a>
My answer is server-based. The controller, which fills the view with model, compares for each image item.ImageURL host with current Request.Url.Host. If they are different (link is external), add attribute to the image link target="_blank", if the same - it adds target="_self". See sample code below, you can easily adjust it to your needs.
//controller
public ActionResult Index() {
var model = new CustomModel {
ImageItems = GetImageItems()
};
//set link target for view based on image url
foreach (var imageItem in model.ImageItems) {
imageItem.LinkTarget = GetLinkTarget(imageItem.ImageURL);
}
return View(model);
}
private string GetLinkTarget(string linkUrl) {
var url = new Uri(linkUrl);
return url.Host == Request.Url.Host ? "_self" : "_blank";
}
//view
<div>
#{
foreach (var imageItem in Model.ImageItems) {
<a class="lnkImage" href="#imageItem.ImageURL" target="#imageItem.LinkTarget">
<img id="PrivateimgPreview" src="#item.ActualImage" />
</a>
}
}
</div>

Select an ID if it's a number?

Is there a way to select a list item from an aspx file from a .cs file to make the <li> visible. The ID for the <li> are numbers.
The reason why they are numbers is because this page is a custom view editor for the website, it is updating a database and then loads the correct view for the user. I need to hide some items for certain users on this page.
Snippet from aspx page:
<div id="connectedSortableLists">
<ul id="unselected" class="connectedSortable">
<li class="ui-state-highlight" id="0">Log #</li>
<li class="ui-state-highlight" id="19">Log date</li>
</ul>
</div
I've tried adding in runat="server" to various places however had no luck.
Is there a way to select like for a grid-view like : grdv_dummy.Columns[29].Visible = false; ?
I want to select the li by an ID to set the visibility to false to do it server side based on user. When the new custom view is saved, database will be updated with the id number. When I try with id="item" the desired page tries to load I get the error Input string was not in a correct format; due to the database having an entry of 'item'.
I feel as though i'm overlooking something although more likely completely wrong.
Thank you for your time
You will definitely need runat=server on your li elements (or ul element). Then you need to add letters to your ids - you can't have just numbers as an id. So something like "item". Then in you .cs file use something like:
private HtmlElement FindListItem(int id)
{
HtmlElement listItem = this.FindControl("item" + id.ToString()) as HtmlElement;
if (listItem != null && listItem.TagName == "li")
{
return listItem;
}
return null;
}
Basically FindControl() is what you need. Then you can use it like:
var item = FindListItem(19);
if (item != null)
{
item.Visible = false;
}
Oh an depending on how you've setup your code, you'll use it either in Page_Load or onPreRender...
you cannot directly access it in server side.However, you can call javascript function from server side which can enable\disable it.
At server side
string jsFunc = "DisableHtmlLi(" + iterator + ")";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "DisableHtmlLi", jsFunc, true);
At Client side
<script type="text/javascript" language="javascript">
function DisableHtmlLi(index) {
var element = document.getElementById(index);
element.visible= false;
}
</script>
Managed to find a way round the problem. I know that li shouldn't be put in other li , but it worked for me.
ASPX Altered
<div id="connectedSortableLists">
<ul id="unselected" class="connectedSortable">
<li class="ui-state-highlight" id="0">Log # </li>
<li class="ui-state-highlight" id="19">Log date</li>
<li runat="server" id="full" visible="false">
<li class="ui-state-highlight" id="32">Days Country</li>
<li class="ui-state-highlight" id="33">Days total</li>
</li>
</ul>
</div
.CS Page
full.Visible = true;

Extract text from a div

I am trying to make a DropDownList using divs and jquery (so that I can style it as I want)...and its working but the problem is I cant get the selected value from the list..
After selection of the option I am copying the selected value into the a div.. and I want to extract this using c# (in .aspx.cs page)... I've tried to do it using string builder and innerHtml(after adding runat="server" to the div).. but it doesn't work ...code is as follows
.aspx Page:
<div class="ddl">
<div id="lowertriangle" class="lowertriangle"></div>
<div id="uppertriangle" class="uppertriangle"></div>
<div id="label" class="labeldiv_dd" runat="server"></div>//***This is the div from which I want to extract value***
<div id="options" class="optionsidv_dd">
<ul id="options_ul">
<li id="0">Select One Option</li>
<li id="1">Option 1</li>
<li id="2">Option 2</li>
<li id="3">Option 3</li>
<li id="4">Option 4</li>
<li id="5">Option 5</li>
</ul>
</div>
</div>
aspx.cs page
Method 1 that I tried:
string sel_text = label.InnerHtml;
display_sel_value.Text = sel_text.ToString();
2nd method:
var sb = new StringBuilder();
label.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
string s = sb.ToString();
Kindly point out my mistakes and help me in this regard(in extracting innerHTML of the div that is).
Thanks
No, putting content in a div won't work.
Your example isn't complete enough to see all that happens, but let's assume that you're in a standard <form>, you're setting the div's inner HTML to a value with Javascript and then you're submitting in the standard way.
Then one way to do what you want is to use a hidden input and setting its value attribute instead of its contents.
<input id="label" class="labeldiv_dd" runat="server" type="hidden">
In the codebehind, the C# can retrieve the value from this control after submitting with the .Value property.
Ok guys thx for your replies..I found a way around the problem...I used HiddenField control to store the selected value using jQuery like so
$("#options_ul li").click(function () {
var text = this.innerHTML;
***$('#<%= selectedvalue.ClientID %>').val(text);***
$("#options_ul li").css("background-color", "#c2c2c2");
$(this).css("background-color", "white");
//var prev = this.id;
//document.getElementById("label").innerHTML = text;
toggleHeight();
});
and then accessed it server side using
selectedvalue.value;
PS: "selectedvalue" is id of the hiddenfield control

asp:Image does not show the image

I have this code. This code is a part of my menu items:
<li class="" id="fifth-li">
<ul style="visibility: hidden; display: none;" id="fifth-ul">
<li><asp:HyperLink ID="hpl_undergraduate" runat="server"></asp:HyperLink></li>
<li><asp:HyperLink ID="hpl_graduate" runat="server"></asp:HyperLink></li>
</ul>
<asp:HyperLink ID="hpl_lessons" runat="server">
<asp:Image ID="img_lessons" runat="server" />
<strong></strong>
<em id="em_lessons" runat="server"></em>
</asp:HyperLink>
</li>
And this is a part of my .cs code file:
em_lessons.InnerHtml = lang["MENU_LESSONS"];
hpl_lessons.Text = lang["MENU_LESSONS"];
hpl_undergraduate.Text = lang["MENU_UNDERGRADUATE"];
hpl_graduate.Text = lang["MENU_GRADUATE"];
hpl_lessons.NavigateUrl = "lessons.html";
hpl_undergraduate.NavigateUrl = "lessons-801.html";
hpl_graduate.NavigateUrl = "lesson-802.html";
img_lessons.ImageUrl = "images/lessons.png"; //Here the image url is defined.
This code is for my web page's menu. There are a few more items like this. I add an image to the img_lessons object on the codebehind. But after running the page I get this code:
<li class="" id="fifth-li">
<ul style="visibility: hidden; display: none;" id="fifth-ul">
<li>
<a id="MainContent_hpl_undergraduate" href="lesson-801.html">
Undergraduate
</a>
</li>
<li>
<a id="MainContent_hpl_graduate" href="lesson-802.html">
Graduate
</a>
</li>
</ul>
<a id="MainContent_hpl_lessons" href="lessons.html">
Lessons
</a>
</li>
I was thinking that if I pull out img_lessons between <asp:HyperLink></asp:HyperLink>, the image would have been shown. But no way. I have changed the codes a bit to be cleaner.
The point is not about the image path, is about some programmatic incompetence/inconvenience. Because I do not see a <img id="MainContent_img_lessons" ... /> code on the browser's code view.
As you can see my image does not look. What do you think?
Regards.
When you do this:
hpl_lessons.Text = lang["MENU_LESSONS"];
you are wiping out any and all markup from the inside of the hyperlink.
EDIT: Since it looks like you already have a <em> tag that you have made a server tag, this line:
em_lessons.InnerHtml = lang["MENU_LESSONS"];
should already be setting viewable text, so, really, you should only have to remove the line mentioned above.
You are clearing the hyperlink innerHTML when you are setting the .Text to lang["MENU_LESSONS"]
What you would need to do is change your markup as follows:
<asp:HyperLink ID="hpl_lessons" runat="server">
<asp:Image ID="img_lessons" runat="server" />
<strong><asp:Literal ID="lit_lessons"/></strong>
<em id="em_lessons" runat="server"></em>
</asp:HyperLink>
And then change your code so that it reads
lit_lessons.Text = lang["MENU_LESSONS"];

Categories