Rahul
Rahul

Reputation: 2307

Use URL based on razor method

I want to redirect to particular page. For that I am using some Javascript function in MVC project as::

function rootUrl(url) {                                                    
    var _rootUrl = '@Url.Content("~")';
    var x = url;
    if (url.indexOf(_rootUrl) != 0) {
        x = _rootUrl + "/" + url;
        x = x.replace(/\/\//g, "/").replace(/\/\//g, "/");
    }
    return x;
};

which is being used as ::

var url = rootUrl("Home/Company/") + $(this).val();
window.location.href = url;

But I am getting wrong URL in my browser as::

http://localhost:60294/Home/Company/@Url.Content(%22~%22)/Home/Company/7

Upvotes: 1

Views: 138

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

Why not use Url.Action() directly which gives you url relative to root directory, instead of creating a javascript messy function:

var url = '@Url.Action("Company","Home")' + $(this).val();

Here,Home is the name of Controller and Company is the action of it

Upvotes: 1

Manjar
Manjar

Reputation: 3268

You can't access razor in Js file. When I need the urls from Razor in Js I just define them in the view, like:

<script>
    var _rootUrl = '@Url.Content("~")';
</script>

This will work

Upvotes: 1

Related Questions