16

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.

IrfanRaza
  • 3,030
  • 17
  • 64
  • 89
  • Here is similar question with more elegant solution: http://stackoverflow.com/questions/16092473/dynamically-generated-javascript-css-in-asp-net-mvc – Philipp Munin Apr 18 '13 at 22:32

2 Answers2

34

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) %>);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

Full Disclosure

  • This answer is copy/pasted from another question:
  • This answer is similar to other answers here.
    • This answer uses cshtml pages rather than ascx controls.
    • This answer offers a View-Only solution rather than a Controller-Only solution.
    • I don't think my answer is 'better' but I think it might be easier for some.

Dynamic CSS in a CSHTML File

I use CSS comments /* */ to comment out a new <style> tag and then I return; before the closing style tag:

/*<style type="text/css">/* */

    CSS GOES HERE

@{return;}</style>

Dynamic JS in a CSHTML File

I use JavaScript comments // to comment out a new <script> tag and then I return; before the closing script tag:

//<script type="text/javascript">

    JAVASCRIPT GOES HERE

@{return;}</script>

MyDynamicCss.cshtml

@{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");

}

/*<style type="text/css">/* */

@foreach (var field in fieldList) {<text>

input[name="@field"]
, select[name="@field"]
{
    background-color: #bbb;
    color: #6f6f6f;
}

</text>}

@{return;}</style>

MyDynamicJavsScript.cshtml

@{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
fieldArray = string.Join(",", fieldList);

}

//<script type="text/javascript">

$(document).ready(function () {
    var fieldList = "@Html.Raw(fieldArray)";
    var fieldArray = fieldList.split(',');
    var arrayLength = fieldArray.length;
    var selector = '';
    for (var i = 0; i < arrayLength; i++) {
        var field = fieldArray[i];
        selector += (selector == '' ? '' : ',')
                    + 'input[name="' + field + '"]'
                  + ',select[name="' + field + '"]';            
    }
    $(selector).attr('disabled', 'disabled');
    $(selector).addClass('disabled');
});
@{return;}</script>

No Controller Required (using Views/Shared)

I put both of my dynamic scripts into Views/Shared/ and I can easily embed them into any existing page (or in _Layout.cshtml) using the following code:

<style type="text/css">@Html.Partial("MyDynamicCss")</style>
<script type="text/javascript">@Html.Partial("MyDynamicJavaScript")</script>

Using a Controller (optional)

If you prefer you may create a controller e.g.

<link rel="stylesheet" type="text/css" href="@Url.Action("MyDynamicCss", "MyDynamicCode")">
<script type="text/javascript" src="@Url.Action("MyDynamicJavaScript", "MyDynamicCode")"></script>

Here's what the controller might look like

MyDynamicCodeController.cs (optional)

[HttpGet]
public ActionResult MyDynamicCss()
{
    Response.ContentType = "text/css";
    return View();
}

[HttpGet]
public ActionResult MyDynamicJavaScript()
{
    Response.ContentType = "application/javascript";
    return View();
}

Notes

  • The controller version is not tested. I just typed that off the top of my head.
  • After re-reading my answer, it occurs to me it might be just as easy to comment out the closing tags rather than use the cshtml @{return;}, but I haven't tried it. I imagine it's a matter of preference.
  • Concerning my entire answer, if you find any syntax errors or improvements please let me know.
Jonathan
  • 949
  • 1
  • 11
  • 13