Image Hyperlink in ASP.NET - MVC 4 - asp.net

I try to create a project for the first time in asp.net (mvc4).
and what i try to do is to create a image which is a hyperlink to go to the index page.
i have search a lot of things and it shows very simple to do that.
but i can´t understand why it doesn´t work for me.
someone can give a hand?
Code:
<a href="<%= Url.Action("Index","Home")%><img src="~/Content/imagens/nav-arrow-back.png"/></a>
The Action is "Index" in the controller calls Home.

you miss a quote
<a href="<%=Url.Action("Index","Home")%>"> ...
^
about this quote you missed
For bad request, fix the whole <img> part
<img src="<%=Url.Content("~/Content/imagens/nav-arrow-back.png")%>"/>

First up, as previously noted you're missing a closing quote on that href. Second, MVC 4 doesn't use the <% %> syntax, at least not by default; it should be using Razor v2 which uses #, so your code should look like this:
<img src="~/Content/imagens/nav-arrow-back.png"/>
If you use the old syntax I assume it would try to handle the actual text <%= Url.Action("Index","Home")%> as a URL, which clearly won't work.

Related

ASP.NET ResolveUrl returns only root

I am wondering why ResolveUrl() function removes href attribute value and whatever I pass as a URL string ultimately leads to http://localhost:PORT. For example:
SomeText
resolves to
<a href>SomeText</a>
[EDIT] A workaround that helped me, but didn't solve the actual problem:
I didn't put the URL in ResolveURL function. I added the runat="server" instead. Like so:
SomeText
Use single-quotes like this:
<a href='<%= ResolveUrl(#"~/Home.aspx?param=1") %>'>SomeText</a>
Please mark as correct answer if this helped you :)

Turining An HTML <td> into a link ASP.NET MVC

I'd like to be able to turn rows of an html table into links to controllers.
I figured something like
<td onclick="<%:Html.ActionLink("", "Index", new {id=item.user_id}) %>">
I'm using MVC 2
Thanks.
<td onclick="window.location='<%:Url.Action("Index", new {id=item.user_id}) %>'">
The onclick attribute accepts some javascript code to execute. If you simply give it a URL, javascript doesn't know what to do with that.
In the snippet above, you're setting the window.location property to the desired URL. This causes the browser to go there.
EDIT: I also just realized that you were using the Html.ActionLink() method which actually generates an tag in your code. You'd be better off using the Url.Action() method, which actually generates a URL.

Why does ASP.Net rewrite relative paths for runat=server anchor controls?

I have my UserControls in a ~/Controls folder in my solution:
/Controls/TheControl.ascx
If specify the following:
<a id="theId" runat="server" href="./?pg=1">link text</a>
ASP.Net seems to want to rewrite the path to point to the absolute location. For example, If the control is on site.com/products/fish/cans.aspx the link href will be rewritten to read
<a id="munged_theId" href="../../Controls/?pg=1>link text</a>
Why does Asp.Net rewrite these control paths, and is there an elegant way to fix it?
I just want the anchor control to spit out exactly what I tell it to!!! Is that so hard?
EDIT:
I've basically done what Kelsey suggested. I knew I could do it this way, but I don't like adding markup in my code when I want something relatively simple. At least it solves the problem:
Aspx page:
<asp:PlaceHolder ID="ph" runat="server"></asp:PlaceHolder>
Code-behind:
var anchor = new HtmlGenericControl("a") { InnerText = "Previous" + " " + PageSize) };
anchor.Attributes["href"] = "?pg=" + (CurrentPage - 1);
anchor.Attributes["class"] = "prev button";
ph.Controls.Clear();
ph.Controls.Add(anchor);
As you can see by the amount of code needed for what is essentially supposed to be be a simple and light-weight anchor, it's not the most optimal solution. I know I could use a Literal but I figured this was cleaner as I'm adding more than one anchor.
I would be interesting in knowing WHY ASP.Net takes over and tries to fix my URL, though.
Why do you have runat="server" and no ID defined? Do you need to access it server side? If you remove the runat="server" everything will work as expected.
For more information regardinging how ASP.NET handles paths check out this MSDN article.
Edit: You can get around the problem then by using a Literal control and then outputing the raw <a href... to it.
Eg:
<asp:Literal ID="myLiteral" runat="server" />
myLiteral.Text = "link text";
Then you can set the visible property on the Literal however you want.
I know this is a bit of an old topic, but I was running into this problem as well and in the end went with a similar solution, but was able to save a few lines of code by doing this in the ascx:
<anchor id="myAnchor" runat="server" href="xxx">link text</anchor>
Then in the code behind, I referenced it using an HtmlGenericControl and can then do this:
myAnchor.TagName = "a";
// other properties set as needed
Anyway, I thought I'd post in case anyone else stumbles in here with the same issue.
Best bet is to make everything app root relative using the magic ~/ lead-in to the url. That tends to keep stuff straight.
There isn't a great answer to your question. ASP.NET is going to treat a relative path in a UserControl as relative to the path of the user control.
What you can do is in the code behind for your user control, set the HRef property of your anchor tag based on the Request.Path property. Then you can create URLs relative to the page.
Alternative is to use a literal like Kelsey was suggestion, or I would just try and map everything app relative with ~/ like Wyatt suggested.
Even a literal doesn't work using ICallBackEventHandler and RenderControl at least... I ended up hacking the tag back client-side :/ e.g in JQuery:
$('#munged_theId').attr('href', './?pg=1');

How to remove portion of url when using NavigateURL

I am using NavigateURL to dynamically pull in the url of products on a receipt page.
Here is the exact code:
<a class="blue13" href="<%#Eval("Product.NavigateUrl")%>"><%#Eval("Product.Name")%></a>
It is placing "/checkout/~/" in each of the url.
How can I remove or correct this?
Thanks!
The simplest thing would probably be to just call .Replace() and replace the unwanted part with a empty string. But it depends relay. Why is it there to begin with? Where is the data coming from?
I ended up switching from a regular href to an asp:HyperLink and it corrected the /~/ issue.
So, before I was using
<a class="blue13" href="<%#Eval("Product.NavigateUrl")%>" runat="server"><%#Eval("Product.Name")%></a><br/>
And I switched it to:
<asp:HyperLink CssClass="blue13" runat="server" NavigateUrl='<%#Eval("Product.NavigateUrl")%>' Text='<%#Eval("Product.Name")%>'></asp:HyperLink>
Which correct the issue.
Thanks.

How do i get rid of __o is not declared?

I have some code in my master page that sets up a a hyperlink with some context sensitive information
<%If Not IsNothing(Profile.ClientID) Then%>
<span class="menu-nav">
<a target="_blank"
href=
"http://b/x.aspx?ClientID=<%=Profile.ClientID.ToString()%>&Initials=<%=Session("Initials")%>"
>
Send
<br />
SMS
<br />
</a>
</span>
<%End If %>
<span class="menu-nav"> <!-- Name __o is not declared Error is flagged here-->
Now the issue seems to be in the href part. If I remove the dynamic code the error disappears. Can anyone tell me how to resolve this issue?
I've found the answer on the .net forums. It contains a good explanation of why ASP.Net is acting the way it is:
We have finally obtained reliable repro and identified the underlying issue. A trivial repro looks like this:
<% if (true) { %>
<%=1%>
<% } %>
<%=2%>
In order to provide intellisense in <%= %> blocks at design time, ASP.NET generates assignment to a temporary __o variable and language (VB or C#) then provide the intellisense for the variable. That is done when page compiler sees the first <%= ... %> block. But here, the block is inside the if, so after the if closes, the variable goes out of scope. We end up generating something like this:
if (true) {
object #__o;
#__o = 1;
}
#__o = 2;
The workaround is to add a dummy expression early in the page. E.g. <%="" %>. This will not render anything, and it will make sure that __o is declared top level in the Render method, before any potential ‘if’ (or other scoping) statement.
An alternative solution is to simply use
<% response.write(var) %>
instead of
<%= var %>
Yes, I have experienced the same bug occasionally in pages that use server side constructs on ASPX pages.
Overtime, I found a fix for it (I'm sorry, I just haven't been able to find out where I found this bit of info again.) and that fix is to put the following code above the errant <%...%> block:
<%-- For other devs: Do not remove below line. --%>
<%="" %>
<%-- For other devs: Do not remove above line. --%>
Apparently, where you put the above code makes all the difference to VS.NET, so it may take a few tries to get it right.
This is an odd solution, but for me I managed to fix this problem by simply closing the offending open files in Visual Studio.
With them open, i was erratically getting the __o problem.
As soon as I closed them, the __o problem disappeared.
After some hours of googling and analyzing bunch of aspx'ses in my current project seems I've found the solution, that is working for me. Would to advise strongly avoid html-style comments:
<!-- ... -->
inside aspx page. Instead of it use aspx-style comments
<%-- ... --%>
Additionally it helped me obtain that vs intellisense and code highlighting became working again and the mainly thing - this case had begun from it - vs can now hit the breakpoints inside embedded pieces of vb/cs code! And no any damn "This is not a valid location for a breakpoint" message.
When I've cleaned the solution, restarted IIS and it is still mysteriously playing up, I find this can sometimes be caused by pasting an ASPX source file's contents from another system into Visual Studio which "helpfully" updates the code, possibly changing some IDs and breaking the page.
Pasting it into another editor (Notepad++?) then saving it stops Visual Studio from "being helpful" and the page works again.

Resources