Href Link Code Behind - c#

I am trying to add a a link as part of the Product.Text but I've horribly got it wrong here, doing this on the C-Sharp code behind.
tcProduct.Text = "<div class=\"productname\">" + "<a class=\"productnameLink\" href=\"item.Product.Url\">" + item.Product.Name + "</a>" + "</div>";
The backward slashes are beginning to confuse me. Instead of a normal hyperlink i guess i should be using the .NET hyperlink instead??
I've tried this but doesn't add the hyperlink;
HyperLink productNameLink = new HyperLink();
productNameLink.Text = "<div class=\"productname\">" + item.Product.Name + "</div>";
productNameLink.NavigateUrl = item.Product.Url.ToString();
productNameLink.CssClass = "prodNameLink";
tcProduct.Controls.Add(productNameLink);

Plain string formatting should do the trick:
tcProduct.Text = string.Format("<div class=\"productname\"><a class=\"productnameLink\" href=\"{0}\">{1}</a></div>",
item.Product.Url, item.Product.Name);
However, you really better use a Repeater which is meant exactly for such things. Markup:
<asp:Repeater ID="rptProducts" runat="server">
<HeaderTemplate><h1>Products</h1></HeaderTemplate>
<ItemTemplate>
<div class="productname"><a class="productnameLink" href="<%# Eval("Url") %>"><%# Eval("Name") %></a></div>
</ItemTemplate>
</asp:Repeater>
And in the code behind:
rptProducts.DataSource = arrProducts;
rptProducts.DataBind();
Where arrProducts is the collection of your products.

What i used to do that is ASP Literal.
<asp:Literal ID="Literal2" runat="server"></asp:Literal>
Then in the code set to it with
Literal2.Text = "<a class='productnameLink' href=" + item.Product.Url + ">" + item.Product.Name + "</a>"

You can use Panel control which renders as div.
var link = new HyperLink
{
Text = item.Product.Name,
NavigateUrl = item.Product.Url.ToString(),
CssClass = "prodNameLink"
};
var panel = new Panel
{
CssClass = "productname"
};
panel.Controls.Add(link);
tcProduct.Controls.Add(panel);
Output:
<div class="productname">
<a class="prodNameLink" href="http://www.google.com">Google</a>
</div>

The Text property is supposed to be text only.
Many ways to do what you need to, but if you want to stick to using html string you could use:
tcProduct.Controls.Add(new HtmlGenericControl
{
InnerHtml = string.Format(#"<div class=""productname""><a class=""productnameLink"" href=""{0}"">{1}</a></div>", item.Product.Url, item.Product.Name )
});
Bonus, you can get rid of the '\' escape char with averbatim string literal: #"" (you need to double the quotes).

Related

Tags Selectively Stripped From Html Elements from Source

We have an asp.net webform pulling markup from a database and sending to browser to render as html.
Html is being selectively stripped from html tags from only some of this markup and is instead displaying as plain text.
I have checked source and all of the tags are there so it's unlikely to be a server issue with the asp controller (I checked anyway, see below) - I have checked the validity of the html at validator.w3c.org and there is nothing the browser should be removing as invalid.
The controller on the webform is asp:literal so I thought it might have been in the wrong mode, however I have played around with this and there is no improvement. Also, some of the html was being rendered correctly anyway so this was always unlikely to be the issue.
I think it might have something to do with a network request overriding some styling as it initially renders correctly but as the page loads additional paints remove the tags from displayed page. Previews of the module in question in network tab also render correctly.
Ok, so the code in source is:
<div class='classname class'>
<div class='classname'>
<div class='classname'><img id = 'myImg' src='https://imgurl.com' alt='A Description'></div>
</div>
<div class='classname'>
<h1>A Heading of My Subject</h1>
<p class='classname'>And then some more.</p>
</div>
<div id='myId'>
<div class='classname'>
<h1> A Heading of My Subject </h1>
<p>Stripping subject from text.</p>
<h2> A Secondary Heading for More Info</h2>
<p>An abstraction of my paragraph text.</p>
<h2> Another Secondary Heading </h2>
<p>Lorem Ipsum forever!</p>
<p>And yet another paragraph.</p>
</div>
</div>
</div>
The actual html rendered is:
<div class='classname class'>
<div class='classname'>
<div class='classname'><img id = 'myImg' src='https://imgurl.com' alt='A Description'></div>
</div>
<div class='classname'>
<h1>A Heading of My Subject</h1>
<p class='classname'>And then some more.</p>
</div>
<div id='myId'>
<div class='classname'>
" A Heading of My Subject
Stripping subject from text.
A Secondary Heading for More Info
An abstraction of my paragraph text.
Another Secondary Heading
Lorem Ipsum forever!
And yet another paragraph."
</div>
</div>
</div>
It is curious that the double quotes are being added also, not sure what is going on there.
The relevant code-behind is:
Page.Title = Name + " - " + Var;
LocOutput.Append("<div class='classname'>" + Environment.NewLine);
LocOutput.Append("<div class='classname'>" + Environment.NewLine);
LocOutput.Append("<div class='classname'><img id='asd' src='" + imgurl + "' alt='" + imgdescription + "'></div>" + Environment.NewLine);
LocOutput.Append("</div>" + Environment.NewLine);
LocOutput.Append("<div class ='classname'><h1>" + Name + "</h1><p class='classname'>" + Name2 + "</p></div>" + Environment.NewLine);
LocOutput.Append("<div id = 'idNameo'><div class ='classname'>" + Content + "</div></div>" + Environment.NewLine);
if (myVar == "condition")
{
LocOutput.Append("<div id = 'idNameod2' value = '" + Var3+ "'></div>" + Environment.NewLine);
}
LocOutput.Append("</div>" + Environment.NewLine);
LocationDetails.Text = LocOutput.ToString();
The stripped away html is located entirely within the Content variable.
The control is :
<asp:Literal ID="LocationDetails" runat="server"/>
The cause in this case was some javascript stripping html as part of an insertion of data following an AJAX call:
var desc = $('#elemId').find('.more').text();
desc = desc.replace("(random data)", randomDataVar);
The method was accessing inner text but after the replacement was inserting it back into innerHTML.
I accessed innerHTML directly to solve this issue:
var desc = document.getElementsByClassName('more')[0];
desc.innerHTML = desc.innerHTML.replace("(random data)", randomDataVar);

Remove Span tag generated in asp.net text label

I cannot remove the span tag which auto generated with the image tag.
Asp.net Code :
if (!IsPostBack)
{
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
SiteManagementService siteMng = new SiteManagementService();
LogedUserDTO logedUser = siteMng.GetLogedUserByUserId(Session["UserLoginID"].ToString().Trim());
LabelUser.Text = logedUser.FullName + " | " + logedUser.Company.CompanyDesc;
**LabelImage.Text = "<img src=\"" + siteMng.GetUserImageUrl() + logedUser.ProfileImage + "\" class='img-avatar' />";**
LabelDatetime.Text = DateTime.Now.ToString();
Session["UserAccessLevel"] = logedUser.UserGroupId;
Session["UserCompanyId"] = logedUser.CompanyId;
RepeaterMenu.DataSource = siteMng.GetMenuByUserGroup(logedUser.UserGroupId);
RepeaterMenu.DataBind();
LabelMasterFooter.Text = "© 2013 " + ResourceData.CompanyName + ". All rights reserved.";
}
Front End Code :
<asp:Label ID="LabelImage" runat="server" ></asp:Label>
Generated HTML Code :
<span id="ContentPlaceHolderHeader_LabelImage"><img src="UploadedFiles/ProPicturs/Img_1711.JPG" class="img-avatar"></span>
Code i want is just
<img src="UploadedFiles/ProPicturs/Img_1711.JPG" class="img-avatar">
If you want to only use an image tag, there is an Image tag in asp.net
protected string image_tag; // add this var in your page class and set it as protected
...
if (!IsPostBack)
{
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
SiteManagementService siteMng = new SiteManagementService();
LogedUserDTO logedUser = siteMng.GetLogedUserByUserId(Session["UserLoginID"].ToString().Trim());
LabelUser.Text = logedUser.FullName + " | " + logedUser.Company.CompanyDesc;
image_tag = "<img src=\"" + siteMng.GetUserImageUrl() + logedUser.ProfileImage + "\" class='img-avatar' />";
LabelDatetime.Text = DateTime.Now.ToString();
Session["UserAccessLevel"] = logedUser.UserGroupId;
Session["UserCompanyId"] = logedUser.CompanyId;
RepeaterMenu.DataSource = siteMng.GetMenuByUserGroup(logedUser.UserGroupId);
RepeaterMenu.DataBind();
LabelMasterFooter.Text = "© 2013 " + ResourceData.CompanyName + ". All rights reserved.";
}
you can try to use in .aspx page.
<%= image_tag %>
instead of
<asp:Label ID="LabelImage" runat="server" ></asp:Label>
A Label Control will add a HTML element to the page. Either as a div or a span element. So this
<asp:Label ID="Label1" runat="server" CssClass="MyLabel">
Content...
</asp:Label>
Becomes this
<span id="Label1" class="MyLabel">
Content...
</span>
But a PlaceHolder does not generate it's own html element. So the following code
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
Content...
</asp:PlaceHolder>
Will generate
Content...
But there are some downsides, as a PlaceHolder does not have a CssClass property.

Code Generated Objects within a loop, blank duplicates show up before them

So I am creating a web page for an audio hire enquiry system. The items are held in a database with info such as Brand, Model, Cost per day, Type etc.
I need to load the webpage with a label, image, button and text box for each item in the database (which will grow and shrink over time).
To do this I query the database to find the total number of items, and then generate and populate the items within this loop (Which is a mix between HTML and C# code blocks); (I have removed some small formatting things such as line breaks etc to make it easier to read)
<% for (int i = 1 ; i <= total; i++)
{
brand = getBrand(i, conString);
name = getName(i, conString);
price = getPrice(i, conString);
type = getType(i, conString); %>
<asp:Label ID="lblName" CssClass="name" runat="server"/>
<% (lblName).Text = (brand + " " + name);
lblName.ID = "lblName" + i; %>
<asp:Image ID="imgItem" runat="server" Width="325px"/>
<% imgItem.ImageUrl = (#"~\Images\" + brand + "_" + name + ".jpg");
imgItem.ID = "imgItem" + i; %>
<asp:Label ID="lblPrice" CssClass="info" runat="server"/>
<% lblPrice.Text = ("£" + Convert.ToString(price) + " per day");
lblPrice.ID = "lblPrice" + i; %>
<asp:Button id="btnAdd" text="Add" runat="server" onClick="btnAdd_Click"/>
<asp:TextBox ID="txtQty" TextMode="Number" Width="24px" CssClass="quantity" runat="server">1</asp:TextBox>
<% btnAdd.Load += new EventHandler(btnAdd_Click);
btnAdd.ID = Convert.ToString(i);
txtQty.ID = ("txtQty" + i); %>
<asp:Image CssClass="rule" runat="server"/>
<% }%>
However, when it generated the web page, it does not start on the first item, it starts with blank version of the objects before their ID's get changed (eg, btnAdd instead of 1, 2, etc):
I've searched all over and cannot find a solution.
-Setting the view state to false in the designer gets rid of all the objects, not just the first ones (which are the only ones that show up in the designer).
-Deleting them from the designer deletes the lines of code, and re-adding the lines of code adds them back to the designer
Any help or anything to point me in the right direction of somewhere that would help is very much appreciated.
Thanks,
Ben

Setting background image in a repeater

I am trying to set a background image in a repeater programmatically. Variations of the following have not worked, including trying to set the url in the div, not the jquery function:
The JQuery function:
var getBackgroundImage = function (imagePath) {
var backgroundImage = 'url(' + iipServ + '?FIF=/IIPServer/images/' + imagePath + '&WID=40&CVT=PNG' + ')';
return backgroundImage;
};
The ASP page:
<asp:Repeater ID="docResults" runat="server" ItemType="ArchiveViewer.Models.Document"
SelectMethod="GetSearchResults" >
<ItemTemplate>
<div class="result" data-docid="<%#:Item.DocumentId %>"
data-imageDir="<%#:Item.FolderPath %>"
data-objData="<%#:Item.JSONPath %>"
style="<%= getBackgroundImage(Item.Pages.First().ImagePath) %> ">
<%#:Item.Metadata.Title %>
</div>
</ItemTemplate>
</asp:Repeater>
Can this be done? How?
Thank you!
EDIT: Each div has its own image. I'm getting the URL from the server.
EDIT 2: I am not instead of using a jquery function, am using a web method in my code behind:
[WebMethod]
public string getBackgroundImage(string path)
{
string iipServer = ConfigurationManager.ConnectionStrings["iipServer"].ConnectionString;
string urlString = "background-image : url('" + iipServer + "?FIF=/IIPServer/images/" +
path + "&WID=40&CVT=PNG)'";
System.Diagnostics.Debug.WriteLine(urlString);
return urlString;
}
In the ASPX page:
style="background-image : <%=getBackgroundImage(Item.Pages.First().ImagePath) %>">
In the code behind:
public string getBackgroundImage(string iipServ, string path)
{
return "url('" + iipServ + "?FIF=/IIPServer/images/" + path + "&WID=40&CVT=PNG)'";
}
It's not clear what iipServ is and where to take it from. Just pass it to the C# function along the path.
You should remove the JS function, this will be all server-side.
pid: Your answer is almost correct, but the compiler didn't like it. It helped me figure out how to do it correctly, though. Thank you.
In case it helps someone else, here is how I fixed this issue:
My ASPX page:
<ItemTemplate>
<div class="result" data-docid="<%#:Item.DocumentId %>"
data-imageDir="<%#:Item.FolderPath %>" data-objData="<%#:Item.JSONPath %>"
style="<%#: getBackgroundImage(Item.Pages.First().ImagePath) %>" >
<%#:Item.Metadata.Title %>
</div>
</ItemTemplate>
And my code behind:
[WebMethod]
public string getBackgroundImage(string path)
{
string iipServer = ConfigurationManager.ConnectionStrings["iipServer"].ConnectionString;
string urlString = #"background-image:url("
+ iipServer + "?FIF=/IIPServer/images/" +
path + "&WID=40&CVT=PNG)";
return urlString;
}

Setting Navigation url to hyperlink dynamically

Im trying to set navigation url to a hyperlink which is inside a gridview.
Im creating the table inside the gridview using a literal in backend c# code.
The code now look like inside GridviewRowDataBound(object sender, GridViewRowEventArgs e)
Literal.Text += "<asp:HyperLink ID='hlContact' runat='server' NavigateUrl='#'>Contact </asp:HyperLink>";
I want to set the navidation inside this code
If anyone have an idea it will be helpful
Thanks
You should just create a HyperLink control, instead of trying to add one to a literal:
HyperLink lnk = new HyperLink();
lnk.Text = "Hello World!";
lnk.NavigateUrl = "~/somefolder/somepage.aspx";
e.Row.Cells[0].Controls.Add(lnk);
If your approach can work, you could try something like this:
Literal.Text += String.Format("<asp:HyperLink ID=\"hlContact\" runat=\"server\" NavigateUrl=\"{0}\">Contact</asp:HyperLink>", navigationUrl);
If you want to use a Literal control though, I would do something like this instead:
Literal.Text += String.Format("Contact", navigationUrl);
If you are just trying to simply databind a HyperLink field in a GridView with a bound field, you can use a TemplateField. Here is an example to do it up front and not the hassle of adding it in the code behind.
<asp:TemplateField HeaderText="Contact" SortExpression="LastName, FirstName">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# String.Format("~/Page.aspx?ID={0}", Eval("CustID").ToString()) %>'>Contact</asp:HyperLink>)
</ItemTemplate>
</asp:TemplateField>
When we writing html content to the literal, it won't picking up the asp hyperlink correctly. But when I used the normal “a” tag, it taking the redirection path correctly.
literal.Text += "a ID='linkcontact' runat='server' href='" + "www.website./pagename.aspx?ID=" + id + "'>contact</a>";
for make a menu and submenu code c#. with variables and navigateurl is of form next
<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
<Items>
<asp:MenuItem>
<asp:MenuItem></asp:MenuItem>
<asp:MenuItem></asp:MenuItem>
</asp:MenuItem>
</Items>
</asp:Menu>
NavigationMenu.Items[0].Text = "xxxxxx"; name of menu
MenuItem menu = NavigationMenu.Items[0];
MenuItem submenu = new MenuItem("xxxxxx"); //name of submenu
submenu.NavigateUrl = "~/Main/xxxxx.aspx?id=" + id + "";
MenuItem submenu1 = new MenuItem("xxxxxxx");//name of sumbenu1
submenu1.NavigateUrl = "~/Main/xxxxxxx.aspx?id=" + id + "";
menu.ChildItems.Add(submenu);
menu.ChildItems.Add(submenu1);

Categories