Url.Content() not working on complex URLs - asp.net-mvc

I have Url.Content() snippets everywhere in my views. They work fine on pages with a simple URL, but not when the URL gets longer.
Here's a sample:
<img src="#Url.Content("~/Content/Images/logo.png")" id="logo">
This works fine when I'm on the homepage, or a page with URL localhost:8080/s/chocolate (which shows the result for the "chocolate" search.
But when I'm trying to add some refinements, e.g. localhost:8080/s/chocolate/b/lindt (which means filter the previous results to only ones from brand Lindt), it doesn't work anymore. In this case, Url.Content points to /s/chocolate/Content/Images/logo.png, which obviously fails.
It's as if Url.Content only goes 2 levels up the current location instead of using the real root of the web app. I guess it makes sense in the convention that URLs are in the form host/controller/action, but here I have a more complex URL scheme (I use URL rewriter module to match these URL fragments to action's parameters).
Is there any way to tell the helper to go to the real root, or any other solution to this problem?
(BTW, I'm using MVC 4)
EDIT:
As Felipe answered, I've just discovered that Url.Content is no longer necessary with MVC 4. That works for all "design" images with a constant path. However, I use a lot of images where the path is constructed partly with some data, e.g.
<img src="#Url.Content(string.Format("~/Content/Images/stores/{0}.png", cart.Store.Retailer.Id))"/>
I simply removed the Url.content, as such:
<img src="#string.Format("~/Content/Images/stores/{0}.png", Model.PreferedCart.Store.Retailer.Id)"/>
When rendered, this gives the following src: ~/Content/Images/stores_v2/Fr_SimplyMarket.png. The ~ being still here, the image is not found. How can I fix that?

In ASP.NET MVC 4+, you do not need to use Url.Content in attribute values. Use the ~/ syntax directly and let razor view engine 2 process the path for you. So your examples can be coded as follows:
<img src="~/Content/Images/logo.png" id="logo">
In the case you need to create a dynamic path, so, you have to use Url.Content, for sample:
#{
string imagePath = Url.Content("~/Content/Images/stores/" + Model.PreferedCart.Store.Retailer.Id + ".png");
}
<img src="#imagePath"/>
If it does not work, the reason is because you have problems with your URL rewriter.

In ASP.NET Core 5, It's working fine using below code in razor page.
#{
string logoPath = Url.Content("~/img.jpg");
}
<div style="background-image:url(#logoPath);">

Related

html.beginform v old skool form tag

What is the benefit to using Html.BeginForm?
We're having some issues related to html helpers and razor generator view testing and I'm struggling to see the benefit which would stop us going back to old skool form tags.
Has anyone got an argument for or against either?
by old skool i mean:
<form action="#Url.Action('Blah')">
The Html.BeginForm is useful because it generates the url using the routes defined in the Global.asax. (or you can extend it with your own code)
Using the old tag is neither worst or best in my opinion. You simply have to generate your url manually or using the Url helper. In the end the html in the page will be the same
<form ....>
html
</form>
Html.BeginForm also implements IDisposable, meaning the form must be closed properly. It's a minor thing, perhaps, but not closing Html.BeginForm produces a run-time error, where an unclosed <form> tag does not.
no there is no difference , the form tag just use the routing to generate the url , so if you use #Url.Action you are good to go
there is even books use that way a plain old tag and a url helper to generate the route
ASP.NET MVC Website Programming is an example
Edit
**
starting from Mvc 4 there is no difference , prior to Mvc 4 , Mvc 3 for example require the Html.BeginForm to make the javascript unobtrusive validation to work

ASP.NET MVC urls for subsites

In my Views I have urls mapped like /My/Urls.something, for example in links (when I don't use View helpers), including static content like images, and mostly in javascript code (Ajax calls and the like).
This works fine when I deploy my app in a first level domain, like http://mysite.com/ because the / before the Url remaps it to the root of the domain, but if the site is deployed as a subsite, for example http://mysite.com/myapp/, this doesn't worka anymore, and omitting the / (for example /My/Urls.something -> My/Urls.something) doesn't work in inner pages like http://mysite.com/myapp/admin where I want to read http://mysite.com/myapp/My/Urls.something but I get http://mysite.com/myapp/admin/My/Urls.something.
Any help?
You should always use view helpers. Even if you don't want to use the ActionLink helper, you should use the Url.Action helper to generate your url. Why? Because of the very problem you're trying to solve, which the helpers were designed to fix.
For example:
<a href="#Url.Action("Index", "Home")" />

Images' site don't loading with a specific url in mvc

I'm using ASP.NET MVC 1.0 and I try to create a personal blog!
I have a problem with an url that it has to show all post wrote in a specific year and specific month.
My url is look like(http://localhost:2282/Blog/Archive/2010/5).
So... it work correctly, infact it show all record that have year=2010 and month=5 but my problem is that when I use this url, images in total my site are no longer loading.
I have this problem only with this url's type.
I think that the problem maybe is my maproute?
routes.MapRoute(
"ArchiveRoute",
"Blog/Archive/{anno}/{mese}",
new { controller = "Blog", Action = "Archive",anno = #"\d{4}", mese = #"\d{2}" }
);
Why images don't loading with this url?
Thanks
Your View may be referencing images using a relative path that doesn't work based on your current route. URLs you use in your view need to be relative to the resulting action's URL, not the folder where the view is stored.
You could use an absolute path or use <img src="<%=Url.Content("~/images")%>/image.jpg" alt="" /> (replace "~/images" with the path to your images, where "~/" equals the root of your application).
If you're using a Master page, it too should be careful to use something like Url.Content, because the Master can get used by different views that are accessible by different URLs!

ASP.NET MVC 2 parameters throws JS error

My application works fine when I have only one parameter.
e.g.
/Product/Index/2
/Report/Sales/08-2009
But it failes when I add one more part to the url. Let's say I want to add the end month-year parameter to the url routing. Mow it becomes:
/Report/Sales/05-2009/09-2009
I do get both parameters in my action method. I parse it and retrieve the data and pass the Model to the View. With this scenario it throws the client side JS error when I try to access any of the form elements. I get "object expected" error. The same view works fine using just first parameter. What could be the issues here?
I also loose the CSS styles when this error occurs.
Thanks
well, without seeing any code at all this is difficult to troubleshoot, but I'd say it's likely because you are referencing your javascript and css files using a relative path like:
../content/scripts/myjavascript.js
Adding the second url parameter has caused the browser to be unable to find the urls because you have added what looks like an extra level of depth to the url.
You should provide absolute urls to your scripts and css files. An easy way to do this is to use the "ResolveUrl" method like so:
<%= ResolveUrl("~/Content/Scripts/myjavascript.css") %>

Using JQuery with ASP.NET MVC Framework

I have searched the forum, and google for this topic. Most of the articles are talking about using JSON to call the controller/action on the server and do ajax effect on the result.
I am trying to use some very basic JQuery features, like the JQuery UI/Tabs, and JQuery UI/Block for a dialog window. I cannot get these simple samples to work in my MVC project. Any ideas how I should modify these samples? I only need these basic feature now and I can go from here.
Thanks!
Actually I just got it working. The problem is that I need to modify the path to an absolute path to the view page because the relative path doesn't work with the MVC routes {controller}/{action}/{id}.
Thanks!
For info, re the relative path issue - I discussed this here (the same concept applies to any page, not just master pages). The approach I used is like so:
1: declare an extension method for adding scripts:
public static string Script(this HtmlHelper html, string path)
{
var filePath = VirtualPathUtility.ToAbsolute(path);
return "<script type=\"text/javascript\" src=\"" + filePath + "\"></script>";
}
2: when needed (for example in the <head>...</head>) use this method:
<%=Html.Script("~/Scripts/jquery-1.2.6.js")%>
The advantage of this is that it will work even if the web app is hosted in a virtual directory (i.e. you can't use "/Scripts" because you aren't necessarily at the site root) - yet it is a lot clearer (and less messy) than the full script with munged src, i.e.
<script ... src="<%=Url.Foo(...)%>"></script>
I just implemented the jquery autocomplete textbox in one of my asp.net project. I only had to import the js file and drop some code into my aspx page. Could you be more detailled about what sample you are trying to run?
This is quick response!!
I am trying to run this "Simple Tabs" on this page:
http://stilbuero.de/jquery/tabs/
I think it is the same with this one: http://docs.jquery.com/UI/Tabs
I just copied and pasted the whole thing into my MVC view page, with corrected path to the jquery.js and .css files, but the content in the tabs all show up together (two of them are supposed to be hidden). My understanding is that this simple jquery plugin just show and hide content.
I had the exact same problem with the jquery thickbox plugin, that the item marked as "hidden" (the dialog box) will always show up in my MVC view page.
I can understand some of the MVC+Jquery+json articles, but I don't understand why the hide/show doesn't work.
Thanks!
I just made a walkthrough on how to do this:
http://blogs.msdn.com/joecar/archive/2009/01/08/autocomplete-with-asp-net-mvc-and-jquery.aspx

Resources