Search code examples
javascriptasp.net-mvc-2dygraphs

Generate javascript file on the fly in asp.net mvc


Friends,

I am trying to use DyGraph in my application. Please look at the code below -

<head>
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9">
    <title>crosshairs</title>

    <script type="text/javascript" src="dygraph-combined.js"></script>

    <script type="text/javascript" src="data.js"></script>
  </head>

The code uses data.js file containing function to get some static data. I want data.js to be generated using a controller method so that it will generate data using database.

Can anybody help me out to resolve this issue.

Thanks for sharing your valuable time.


Solution

  • You could define a controller action:

    public ActionResult Data()
    {
        // Obviously this will be dynamically generated
        var data = "alert('Hello World');";
        return JavaScript(data);
    }
    

    and then:

    <script type="text/javascript" src="<%= Url.Action("Data", "SomeController") %>"></script>
    

    If you have some complex script that you don't want to generate in the controller you could follow the standard MVC pattern by defining a view model:

    public class MyViewModel
    {
        ... put required properties
    }
    

    a controller action which would populate this view model and pass it to the view:

    public ActionResult Data()
    {
        MyViewModel model = ...
        Response.ContentType = "application/javascript";
        return PartialView(model);
    }
    

    and finally a view which in this case will be the javascript representation of the view model (~/Views/SomeController/Data.ascx):

    <%@ Control 
        Language="C#" 
        Inherits="System.Web.Mvc.ViewUserControl<MyViewModel>" %>
    alert(<%= new JavaScriptSerializer().Serialize(Model.Name) %>);