Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC3 Root-relative path to virtual path in Controller or Model

This sounds like a simple enough question, but can't find the answer for the life of me. How does one convert a root-relative url (~/my/path) to a virtual path (/mywebsite/my/path) in the Controller and/or Model?

On a view it's easy enough to do, just call @Url.Content("~/my/path/"). And getting the physical path in the controller is just as easy using Server.MapPath("~/my/path"). But I can't figure out how to get the virtual path in the controller.

My main issue is that I have a root-relative path of an image that I will be passing to a JSON object that will be returned. In most cases this will be read by javascript and put on the page somewhere, and I can't use @Url.Content in my javascript code. Also, in some instances this JSON object will be used by an external application that won't understand what the ~ means.

like image 782
death_au Avatar asked Jan 20 '12 05:01

death_au


People also ask

Which of the following MVC methods converts a virtual path to a physical path?

MapPath method is used to map the virtual path to a physical path.

What is physical path and virtual path in asp net?

Physical path - This is the actual path the file is located by IIS. Virtual path - This is the logical path to access the file which is pointed to from outside of the IIS application folder.

Is a physical path but a virtual path was expected C#?

Generally this physical and virtual path problem occurred whenever we refer “Server. MapPath” value multiple times while using folder path in applications. To solve this e:is a physical path but a virtual path was expected we need to use Server.

What is MapPath in asp net?

The MapPath method maps the specified relative or virtual path to the corresponding physical directory on the server. Copy. MapPath( Path )


1 Answers

In the controller you could use the Url property:

public ActionResult Foo()
{
    string url = Url.Content("~/my/path");
    ...
}

In the Model you don't do anything like this. A model shouldn't know anything about url generation. It simply not its responsibility. If it needs to work with an url this url should be passed to it by the layers of your application that deal with urls (which are the layers that have access to an HttpContext).

like image 186
Darin Dimitrov Avatar answered Sep 18 '22 02:09

Darin Dimitrov