hasser
hasser

Reputation: 1076

Get site url on mvc

I want to write a little helper function that returns the site url. Coming from PHP and Codeigniter, I'm very upset that I can't get it to work the way I want.

Here's what I'm trying:

@{
    var urlHelper = new UrlHelper(Html.ViewContext.RequestContext);
    var baseurl = urlHelper.Content("~");
}

<script>
    function base_url(url) {

        url = url || "";
        return '@baseurl' + url;
    }
</script>

I want to return the base url of my application, so I can make ajax calls without worrying about paths. Here's how I intend to use it:

// Development
base_url(); // http://localhost:50024

// Production
base_url("Custom/Path"); // http://site.com/Custom/Path

How can I do something like that?

EDIT

I want absolute paths because I have abstracted js objects that makes my ajax calls. So suppose I have:

function MyController() {
   // ... js code
   return $resource('../MyController/:id');
}

// then
var my_ctrl = MyController();
my_ctrl.id = 1;
my_ctrl.get(); // GET: ../MyController/1

This works when my route is http://localhost:8080/MyController/Edit but will fail when is http://localhost:8080/MyController .

Upvotes: 3

Views: 6606

Answers (3)

hasser
hasser

Reputation: 1076

I managed to do it like this:

@{
    var url = Request.Url;
    var baseurl = url.GetLeftPart(UriPartial.Authority);
}

Thank you all!

Upvotes: 2

sergserg
sergserg

Reputation: 22264

Instead of manually creating your URL's, you can use @Url.Action() to construct your URLs.

<p>@Url.Action("Index", "Home")</p>
/Home/Index

<p>@Url.Action("Edit", "Person", new { id = 1 })</p>
/Person/Edit/1

<p>@Url.Action("Search", "Book", new { title = "Gone With The Wind" })</p>
/Book/Search?title="Gone+With+The+Wind"

Now the absolute best reason to go with this option is that @Url.Action automatically applies any vanity URL routes you have defined in your Global.asax file. DRY as the sub-saharan desert! :)


In your case, your can create a 'custom path' in two ways.

Option A)

<p>@Url.Action("Path", "Custom")</p>
/Custom/Path

Option B)

You can create a route using the Global.asax file. So your controller/action combo can be anything you want, and you can create a custom vanity route url - regardless of the controller/action combo.

Upvotes: 0

BZink
BZink

Reputation: 7957

Are you aware of @Url.Action("actionname") and @Url.RouteUrl("routename") ?

Both of these should do what you're describing.

Upvotes: 1

Related Questions