开发者

Correct way to referencing paths in a Javascript file in an ASP.NET MVC app

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 i开发者_运维知识库nstead 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.


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;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜