在 asp.net mvc 中动态生成 javascript 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8133546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:25:03  来源:igfitidea点击:

Generate javascript file on the fly in asp.net mvc

javascriptasp.net-mvc-2dygraphs

提问by IrfanRaza

Friends,

朋友们,

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

我正在尝试在我的应用程序中使用 DyGraph。请看下面的代码——

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

该代码使用包含函数的 data.js 文件来获取一些静态数据。我希望使用控制器方法生成 data.js,以便它使用数据库生成数据。

Can anybody help me out to resolve this issue.

任何人都可以帮我解决这个问题。

Thanks for sharing your valuable time.

感谢您分享您的宝贵时间。

回答by Darin Dimitrov

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:

如果您不想在控制器中生成一些复杂的脚本,您可以通过定义视图模型来遵循标准的 MVC 模式:

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):

最后一个视图,在这种情况下将是视图模型 ( ~/Views/SomeController/Data.ascx)的 javascript 表示:

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

回答by Jonathan

Full Disclosure

全面披露

  • This answer is copy/pasted from another question:
  • This answer is similar to other answers here.
    • This answer uses cshtmlpages rather than ascxcontrols.
    • 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.
  • 这个答案是从另一个问题复制/粘贴的:
  • 这个答案类似于这里的其他答案。
    • 此答案使用cshtml页面而不是ascx控件。
    • 这个答案提供了一个 View-Only 解决方案,而不是一个 Controller-Only 解决方案。
    • 我不认为我的答案是“更好”,但我认为对某些人来说可能更容易。

Dynamic CSS in a CSHTML File

CSHTML 文件中的动态 CSS

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

我使用 CSS 注释/* */来注释掉一个新<style>标签,然后return;在结束样式标签之前使用:

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

    CSS GOES HERE

@{return;}</style>

Dynamic JS in a CSHTML File

CSHTML 文件中的动态 JS

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

我使用 JavaScript 注释//来注释掉一个新<script>标签,然后我return;在结束脚本标签之前:

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

    JAVASCRIPT GOES HERE

@{return;}</script>

MyDynamicCss.cshtml

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

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:

我将两个动态脚本都放入其中,Views/Shared/并且可以_Layout.cshtml使用以下代码轻松地将它们嵌入到任何现有页面(或)中:

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

MyDynamicCodeController.cs(可选)

[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.
  • 控制器版本未经测试。我只是在头顶打字。
  • 重新阅读我的答案后,我发现注释掉结束标记而不是使用 cshtml 可能同样容易@{return;},但我还没有尝试过。我想这是一个偏好问题。
  • 关于我的整个答案,如果您发现任何语法错误或改进,请告诉我。