2
Answers

How To dynamically generate a JavaScript file in an ASP.NET?

Photo of Kripanshu Kumar

Kripanshu Kumar

Sep 30
452
1

How To dynamically generate a JavaScript file in an ASP.NET application using C#?

Answers (2)

4
Photo of Ck Nitin
250 7.7k 3.1m Sep 30

To dynamically generate a JavaScript file in an ASP.NET application using C#, you can create an endpoint (such as an .ashx handler or a Web API endpoint) that generates the JavaScript content and sets the appropriate MIME type for JavaScript.

Accepted
1
Photo of Adarsh Nigam
433 3.3k 37.6k Sep 30

To dynamically generate a JavaScript file in an ASP.NET application using C#, create a controller action that returns the JavaScript content with the appropriate MIME type:

1. C# Controller Action:

public ActionResult GenerateScript()
{
    string jsContent = @"
        function showAlert() {
            alert('Dynamically generated JS!');
        }";
    return Content(jsContent, "application/javascript");
}
 

 2. Reference in View:

<script src="@Url.Action("GenerateScript", "Script")"></script>
 

This will serve a dynamic JavaScript file when the view is loaded.