Ranjini
Ranjini

Reputation: 33

How to render the js content written in a cshtml in a script tag in ASP.Net Core MVC

I have a cshtml file where i declare all my route data.

FileName: _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" })',
}

I also have a Action method in my HomeController

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

In _Layout.cshtml and _LayoutNone.cshtml, I have to get this commonRoutes as js content since im using this routes in the ajax calls in some of the pages

my current implementation is like:

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

Since I'm migrating my code from MVC to ASP.Net Core (.net8). I'm getting 400 Bad Request error in my network tab.

Need help to fix and understand this issue.

Upvotes: 0

Views: 94

Answers (1)

Zhi Lv
Zhi Lv

Reputation: 21571

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

For the above code, after rendering, the output as below:

rendering

So, can't reproduce the 400 error.

I have to get this commonRoutes as js content since im using this routes in the ajax calls in some of the pages

To get the commonRoutes, you can use JQuery ajax to call the GetRoutes action method, like this:

<!-- 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>

The after clicking the Load View button, the result as below:

test result

Update:

How to render the js content written in a cshtml in a script tag in ASP.Net Core MVC

To dynamic load JS content, you can try to use JavaScript to create new script element and then set content, after that append the script to the head or body. Coke like this:

    public IActionResult GetScript()
    {
        Response.ContentType = "text/javascript";
        return this.Content("function ShowAlert() {alert(\"Hello\");}");
    }

And in the view page, use the following code:

    <button id="loadJSBtn">Load JavaScript</button>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <button id="showalert" onclick="ShowAlert()">Show Alert</button>
    <script>
        $(document).ready(function () {
            $('#loadJSBtn').click(function () {

                      // Create a new script element 
                $.ajax({
                    url: '/Home/GetScript', // URL to your controller action
                    type: 'GET',
                    success: function (data) { 
                         //Create a new script element
                        var script = document.createElement('script');
                        script.type = 'text/javascript';
    
                        // Use textContent to set the script content
                        script.textContent = data;
    
                        // Append the script to the head or body
                        document.body.appendChild(script); // or document.head.appendChild(script);
                    },
                    error: function () {
                        alert('Failed to load the partial view.');
                    }
                });
            });

        });
    </script>

Running the application, after clicking the Load JavaScript button and click the Show Alert button, the output as below: as we can see the dynamic JavaScript works well:

enter image description here

Upvotes: 0

Related Questions