如何在ASP.Net Core MVC中的script标签中渲染cshtml中编写的js内容

问题描述 投票:0回答:1

我有一个 cshtml 文件,其中声明了我的所有路线数据。

文件名:_Routes.cshtml

@{ Layout = ""; Context.Response.ContentType = "text/javascript"; }
var commonRoutes = {
  userList: '@Url.RouteUrl("Default", new { Controller = "User", Action = "GetUserList" })',
  location: '@Url.RouteUrl("Default", new { Controller = "User", Action = "GetUserLocations" })',
}

我的 HomeController 中也有一个 Action 方法

public IActionResult GetRoutes()
{
    Response.ContentType = "text/javascript";
    return this.View("_Routes");
}

在 _Layout.cshtml 和 _LayoutNone.cshtml 中,我必须将此 commonRoutes 获取为 js 内容,因为我在某些页面的 ajax 调用中使用此路由

我目前的实现是这样的:

<script type="text/javascript" src='@Url.RouteUrl("Default", new { Controller = "Home", Action = "GetRoutes"})'></script>

自从我将代码从 MVC 迁移到 ASP.Net Core (.net8) 以来。我的网络选项卡中收到 400 Bad Request 错误。

需要帮助来解决和理解这个问题。

javascript asp.net-core-mvc asp.net-core-2.0
1个回答
0
投票
<script type="text/javascript" src='@Url.RouteUrl("Default", new { Controller = "Home", Action = "GetRoutes"})'></script>

对于上面的代码,渲染后输出如下:

rendering

所以,无法重现400错误。

我必须将此 commonRoutes 获取为 js 内容,因为我正在使用它 某些页面的ajax调用中的路由

要获取commonRoutes,您可以使用JQuery ajax调用GetRoutes操作方法,如下所示:

<!-- In your view, where you want to load the view -->
<div id="partialContainer">
    <!-- The view content will be render here -->
</div>

<button id="loadPartialBtn">Load View</button>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function () {
        $('#loadPartialBtn').click(function () {
            $.ajax({
                url: '/Home/GetRoutes', // URL to your controller action
                type: 'GET',
                success: function (data) {
                    // Inject the view content into the container
                    $('#partialContainer').html(data);
                },
                error: function () {
                    alert('Failed to load the view.');
                }
            });
        });
    });
</script>

点击Load View按钮后,结果如下:

test result

© www.soinside.com 2019 - 2024. All rights reserved.