1

Currently what I'm doing in my js file is this (and it works):

    var root = "http://mydomain.com";

$.ajax({
    type: "POST",
    url: root + "/MyController/MyAction",
    data: { 'id': myId },
    dataType: "html",
    success: function (response) {
    blah blah...

However the problem is if someone types in www.mydomain.com instead of mydomain.com, the path is not found. I tried following the advice in this post: Relative Image URL in Javascript File - ASP.net MVC and IIS 7, namely setting root to ../ or document.location.host, but both don't work.

What's the correct way to specify paths (to actions in controllers, images, etc) in a js file?

Thanks.

1 Answer 1

7

In your view:

<script type="text/javascript">
    var url = '<%= Url.Action("MyAction", "MyController") %>';
</script>

and in your external javascript file:

$.ajax({
    type: "POST",
    url: url,
    data: { 'id': postId },
    dataType: "html",
    success: function (response) {
    blah blah...

or even better: if you are AJAXifying an existing link or form:

<%= Html.ActionLink("foo", "MyAction", "MyController", null, new { id = "foo" })

and in your javascript:

$('#foo').click(function() {
    $.ajax({
        type: "POST",
        url: this.href,
        data: { 'id': postId },
        dataType: "html",
        success: function (response) {
        blah blah...
    });
    return false;
});
Sign up to request clarification or add additional context in comments.

8 Comments

I have all my js code in an external javascript file and not embedded in the view, so I can't use <%= Url.Action. That's the problem.
@Prabhu, that's why I started my answer with In your view.
I was going to say regular expression but this is obviously better.
Oh ok got it...so you're saying declare the url in the view and use it in the js file? Not a bad idea actually. Is this the standard way to do it?
@Prabhu, there are two possibilities: either you are AJAXifying an existing element of your DOM such as an anchor or a form in which case you already have the url in the DOM (see second part of my answer) or you don't in which case you could declare it as a global javascript variable.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.