Concat Web.config value and string in Image control SRC - asp.net

I have a web.config key :
<add key="IMGSRC" value="http://localhost" />
I want to use the value of this key along with the path of the image concatenated to in an aspx page. I'm aware that I can get to root folder by simply saying "../ImagesFolder" , but my website has parent path disabled because of security concerns. So now I need to work around it.
I need something like this (Here are a few things I tried after looking up the internet and which did not work.):
1) <img id="Img19" runat="server" alt="Admin" src='<%#ConfigurationSettings.AppSettings["IMGSCR"] %>' />
2) <img id="Img19" runat="server" alt="Admin" src='<%#ConfigurationSettings.AppSettings["IMGSCR"] + "/ImagesFolder/img.jpeg" %> ' />
3)
<img id="Img19" runat="server" alt="Admin" src="<%#ConfigurationSettings.AppSettings["IMGSCR"] %> " + "/ImagesFolder/img.jpeg" />
Also I tried this:
I declared a variable Path on Page_Load
Path = System.Configuration.ConfigurationManager.AppSettings["RootforIMG"].ToString();
and then on aspx page I tried using it as
<img id="Img19" runat="server" alt="Admin" src="<%=Path %> " + "/ImagesFolder/img.jpeg" /> but this as well is no good.

Can you try something like below?
<img id="Img19" runat="server" alt="Admin" src='<%= GetImageSource()%>' />
In code behind
public string GetImageSource()
{
return ConfigurationManager.AppSettings["IMGSCR"] + "/ImagesFolder/img.jpeg";
}

The relative path of images should work:
Relative path can be as per your page location i.e: '../IMages/img.jpg' or 'images/img.jpg'
try this :
<img id="Img19" runat="server" alt="Admin" src='ImagesFolder/img.jpeg' />

For controls with runat="server" attribute you do not need any special code to map a path relative to web site root:
<img id="Img19" runat="server" alt="Admin" src"~/ImagesFolder/img.jpeg" />
The path ~/ImagesFolder/img.jpeg will be resolved replacing ~ with the root folder of your web-site.
If to resolve path you need some kind of logic (for example you need to call a function) then you can use this:
<img src'<%= ResolveImageName() %>' />
Do not forget that URL must be proper encoded.

Related

Append filename to Img src attribute using resource file

When I try to append the image name onto the end of the <%$ Resources:LocalizedText, MyKey %> the server doesn't build the path at all.
This is what I'm doing and it's not working:
<img id="Img2" runat="server" src="<%$ Resources:LocalizedText, ImagesPath %>feature_LED.jpg" />
Is there any way to append?
this will work instead
src="<%= Resources.LocalizedText.ImagePath %>

My <% %> not working in div. Why?

I've tried both snippets below. Nothing. I've tried <%#, <%=, and <%. Nothing. So I'm stuck.
<div style="background-color:Gray; color:white; text-align:center; width:100%;">
<asp:HyperLink ID="HyperLink1" Target="_blank" NavigateUrl='<%= Server.HtmlEncode(String.Format("~/ShowHistory.aspx?section={0}&jobnumber={1}", "APQP Header", "101244")) %>' runat="server">Show Updated History</asp:HyperLink>
<asp:HyperLink Target="_blank" NavigateUrl="~/ShowDeletedHistory.aspx" ID="HyperLink2" runat="server">Show Deleted History</asp:HyperLink></div>
<br />
<div style="background-color:Gray; color:white; text-align:center; width:100%;">
<asp:HyperLink ID="HyperLink1" Target="_blank" NavigateUrl='<%= String.Format("~/ShowHistory.aspx?section={0}&jobnumber={1}", "APQP Header", "101244") %>' runat="server">Show Updated History</asp:HyperLink>
<asp:HyperLink Target="_blank" NavigateUrl="~/ShowDeletedHistory.aspx" ID="HyperLink2" runat="server">Show Deleted History</asp:HyperLink></div>
<br />
Try <%# ... %> and call this.DataBind() (or Me.DataBind()) when your page loads.
Server controls cannot contain this type of tags. The reason is that "<%= %>" is basically equal to Response.Write, which itself executes after the page has gone through its lifecycle, when the response is already constructed. If you use it when setting a value of a server-side control property, this value has to be resolved when (or a little after) parsing the page markup. This is the reason you cannot use "<%= %>" in a server control.
If it was a normal html tag, it would work, but the virtual URL would not.
Is there a reason you're not setting the NavigationUrl in code? It would look much nicer to me.

input losing src

If I use the following code without runat="server" the input's src works fine and I see the image coming through.
<div><input id="testButton" type="image" src="<%=TestButtonImageUrl %>" onserverclick="RedirectTest" /></div>
url is https://fpdbs.paypal.com/dynamicimageweb?cmd=_dynamic-image
But if I put the runat="server" in, for some reason, I get this for the url:
<div><input id="testButton" type="image" src="<%=TestButtonImageUrl %>" onserverclick="RedirectTest" runat="server" /></div>
url is http://localhost/%3C%=lButtonImageUrl%20%%3E
You cannot use the <%= %> syntax with server controls (including standard HTML elements with runat="server"). You have two choices:
Access the control in the code behind (as an HtmlInputControl) and assign the src attribute using the Attributes property: imageControl.Attributes["src"] = value;
Assign the attribute using the databinding syntax (src="<%# %>") and call imageControl.DataBind() from the code behind
Maybe I'm missing something. But runat server tag does not support code expression.
When you add runat="server to that html tag, Asp.Net converts it from string to HtmlControl - in this case of type HtmlInputImage. You can see this happen by adding:
<%= testButton.GetType() %>
Then the only thing you need to do is set the Src-property, which, contrary to other comments, you CAN do in inline aspx - no need for a code-behind file:
<%
testButton.Src = "/content/logo.png";
%>
<input id="testButton" type="image" runat="server" src="" onserverclick="RedirectTest" />
You need to set the Src-property BEFORE the actual input, which is a bit non-intuitive, the reason is that the code is run at render-time, so if the setting of Src-property is after the control, it is too late.
if jQuery is an option than you could try this:
<script type="text/javascript">
$(function() { $('#<%=testButton.ClientID %>').attr('src', '<%=TestButtonImageUrl %>'); });
</script>
...
<div><input id="testButton" runat="server" type="image" onserverclick="RedirectTest" /></div>
Update:
Another option is to create a HttpHandler with processing like this
public void ProcessRequest(HttpContext context)
{
var testButtonImageUrl = "https://fpdbs.paypal.com/dynamicimageweb?cmd=_dynamic-image";
context.Response.Redirect(testButtonImageUrl);
}
add in web.config path to handle image.img or whatever and update aspx
<div><input id="testButton" runat="server" type="image" src="image.img" onserverclick="RedirectTest" /></div>

Why a <a href="~/#link"> when run become <a href="#link#link"> in a master page?

I never saw that problem and I have no idea what is causing it.
I got something like this code in my masterpage
<div class="myClass1">
<a href="~/#link" runat="server" title=" <%$ Resources: myRess1 %>">
<asp:Literal runat="server" Text="<%$ Resources: myRess1 %>" /><br />
<img class="myClass2" src="/MasterPage/images/myGif.gif" width="19" height="12" alt="" />
</a>
</div>
when I browse a page that using this master page, the code become
<div class="myClass1">
<a href="#link#link" title="myTitle">
myTitle<br />
<img class="myClass2" src="/MasterPage/images/.gif" width="19" height="12" alt="" /><br />
</a>
</div>
why does the link double itself?
if I put something like default.aspx instead of #link, it work perfectly.
The reason why I'm using "~/" is because the master page is located somewhere else, if I don't put ~/ it make the link as /masterpage/#link which is invalid
The ~/ should not be necessary. Just use #link
'~' can be used only with server controls and not with html controls. You should just use href="#link".
for now I changed my
<a href="~/#link" runat="server" title=" <%$ Resources: myRess1 %>">
to
<a href="#link" title="<%=GetLocalResourceObject("myRess1 ") %>">
and it's working fine but if someone could tell me why with runat="server" screw up the #link, that would be good to know

sharepoint rendering templates set attributes from fields

I'm trying to write a custom rendering template for use in the DisplayForm of a list whose fields include Title, HeaderImageUrl, Body. I've got the following so far:
<SharePoint:RenderingTemplate ID="NewsListForm" runat="server">
<Template>
<h1><SharePoint:FieldValue FieldName="Title" runat="server"/></h1>
<div>
<p>
<SharePoint:UrlField FieldName="HeaderImageUrl" runat="server"></SharePoint:UrlField>
<SharePoint:RichTextField FieldName="Body" runat="server" />
</p>
</div>
</Template>
</SharePoint:RenderingTemplate>
The HeaderImageUrl field is configured to be an Image URL, but when I use the UrlField control, it renders a link.
I was thinking there might be a way to grab field values and put them in attributes, so something like this:
<asp:Image ImageUrl="<% FieldValue["HeaderImageUrl"] %>" runat="server"/>
If this kind of thing isn't possible, then is there another control in Microsoft.SharePoint.WebControls that would render an image from a URL?
All the examples I've seen of calling a URL field to be displayed as an image have been through C# code. Which is quite annoying since most of web part bits can be written without using C# code. You might also need to go down that road here... perhaps a custom field control or user control.
Even if your code above did get the value for HeaderImageUrl, it wouldn't work as Url values are (confusingly):
[the actual url specified][some wierd delimeter string][the description field of the url (usually the actual url again if your don't specify it)]
So you would need to split the string with te delimeter values and use the [0] (the first) as what you inject into your image url.
Please do post if you find a way to do this without writing C# code.
p.s. Have you considered using a DataFormWebPart which has a xsl section in which you might be able to do extractly what you need?!
Example: You can stick the following syntax into any aspx / ascx file:
<%# Register tagprefix="SharePoint" namespace="Microsoft.SharePoint.WebControls" assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Register tagprefix="WebPartPages" namespace="Microsoft.SharePoint.WebPartPages" assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Register Tagprefix="PublishingWebControls" Namespace="Microsoft.SharePoint.Publishing.WebControls" Assembly="Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<WebPartPages:DataFormWebPart runat="server" IsIncluded="True" FrameType="None"
NoDefaultStyle="TRUE" ViewFlag="0" Title="My List Display"
Default="FALSE" ID="dfwp_MyListDisplay"
DisplayName="My List Display">
<DataSources>
<SharePoint:SPDataSource runat="server" DataSourceMode="List" UseInternalName="true"
selectcommand='<View><Query><Where><Eq><FieldRef Name="Category"/><Value Type="Text">Header</Value></Eq></Where></Query></View>' id="Utility_x0020_Navigation1"><SelectParameters><WebPartPages:DataFormParameter Name="ListName" ParameterKey="ListName" PropertyName="ParameterValues" DefaultValue="My List Display"/>
<asp:Parameter Name="ListName" DefaultValue="LIST NAME" />
<asp:Parameter Name="WebUrl" DefaultValue="<% $SPUrl:~SiteCollection/ %>" />
</SelectParameters>
</SharePoint:SPDataSource>
</DataSources>
<ParameterBindings>
<ParameterBinding Name="dvt_apos" Location="Postback;Connection"/>
<ParameterBinding Name="PageURL" Location="ServerVariable(URL)" DefaultValue=""/>
<ParameterBinding Name="SiteUrl" Location="ServerVariable(SERVER_NAME)" DefaultValue=""/>
</ParameterBindings>
<datafields>#Title,Title;#URL,URL;#Category,Category;#Parent_x0020_item,Parent_x0020_item;#Sort_x0020_Order,Sort Order;#ID,ID;#ContentType,Content Type;#Modified,Modified;#Created,Created;#Author,Created By;#Editor,Modified By;#_UIVersionString,Version;#Attachments,Attachments;#File_x0020_Type,File Type;#FileLeafRef,Name (for use in forms);#FileDirRef,Path;#FSObjType,Item Type;#_HasCopyDestinations,Has Copy Destinations;#_CopySource,Copy Source;#ContentTypeId,Content Type ID;#_ModerationStatus,Approval Status;#_UIVersion,UI Version;#Created_x0020_Date,Created;#FileRef,URL Path;</datafields>
<xsl>
YOUR XSLT HERE
</xsl>
</WebPartPages:DataFormWebPart>
The following code will get you the url of an imagefield:
SPListItem item = GetItem();
string imagefieldhtml = item["HeaderImageUrl"].ToString();
ImageFieldValue imagefield = new ImageFieldValue(imagefieldhtml);
var url = imagefield.ImageUrl;
So maybe altering your to something like this will help you, or maybe help you out atleast...?
<asp:Image ImageUrl="<% (ImageFieldValue ["HeaderImageUrl"]).ImageUrl %>" runat="server"/>
Unable to test it atm (no environment) but I am quite sure I did this before.
Try these:
<SharePoint:FieldValue FieldName="HeaderImageUrl" runat="server"/>
or:
<img src="<SharePoint:FieldValue FieldName="HeaderImageUrl" runat="server"/>" />
I'll check back on this one and do an actual test by monday if those didn't work and you still need help.
Turns out that my problem was simply that I didn't have that image column set up to render as an image, rather than as a link. The builtin Microsoft.SharePoint.UrlField control worked just fine, as it turned out.

Resources