在开发和生产环境中获取基础url

Get base url in dev and production environment

本文关键字:url 获取 开发 生产环境      更新时间:2023-09-26

我使用MVC3并使用jquery构建一个标签(链接)。问题是我只能让我的链接工作在生产或开发,而不是两者。这是我的网站的网址在生产

http://tvap.mydomain.com

这是我的开发url。http://localhost/TVAP

那么,我有一个链接,我正在创建通过jquery如下。

  var actionCell = $('#itemlist').find(rowId).find(actionCellId);
  $('<a>Edit</a>').attr({ 'id': 'edit-' + response.id, 'href': '/Items/Edit/' + response.id }).appendTo(actionCell);

在生产环境中,这可以工作,并创建一个链接

 <a id="edit-17" href="/Items/Edit/17">

但是在开发(本地)中,它不起作用,因为我需要这个。

 <a id="edit-17" href="/TVAP/ItemManagement/Edit/17">

中得到以下内容
 $(location).attr('host') ==> localhost
 $(location).attr('host') ==> http://localhost/TVAP/Items/Index

信息太少或太多。我知道我可以检查localhost并根据需要附加ttap,但这似乎是一种hack。其他开发人员可能会使用ASP。. NET VS开发服务器,并获得一个URL将包含localhost,但没有TVAP,因为我得到。即- http://localhost:64301/Items/Index

这是我在_Layout.cshtml:

<head>
    <!-- other stuff -->
    <script type="text/javascript">
        window.myProjectName = {
            baseUrl : '@Url.Content("~/")'
        };
    </script>
    <!-- other scripts -->
</head>

那么你总是可以使用像myProjectName.baseUrl+"Controller/Action"这样的东西从你自己的javascript文件中访问你的资源。这可以帮助您将视图从javascript中分离出来,这是一件非常好的事情。

你不想把标记和javascript混在一起——这是一个很好的折衷方案。

如果你的JS直接在你的视图中(而不是外部JS文件),你可以使用Razor将url刷新到你的Javascript中。

// untested
var actionCell = $('#itemlist').find(rowId).find(actionCellId);
$('<a>Edit</a>').attr({ 
    'id': 'edit-' + response.id, 
    'href': '@Url.Action("Edit")/' + response.id
}).appendTo(actionCell);