使用 Razor 语法调用 JavaScript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26241459/
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-28 05:42:05  来源:igfitidea点击:

Call JavaScript function with Razor syntax

javascriptc#asp.net-mvcrazor

提问by Stephen Sugumar

I am currently working on an ASP.Net MVC application. From my database, I have created three dictionaries and stored them inside a View Model.

我目前正在开发一个 ASP.Net MVC 应用程序。从我的数据库中,我创建了三个字典并将它们存储在一个视图模型中。

After populating said dictionaries with some logic in the controller, I'm accessing these dictionaries in my View via @Model

在控制器中使用一些逻辑填充所述字典后,我正在通过以下方式在我的视图中访问这些字典 @Model

After manipulating these dictionaries, I need to send the data to a JS function to apply some logic to a JS library called DHtmlxScheduler

操作完这些字典后,我需要将数据发送到一个 JS 函数,以将一些逻辑应用到一个名为DHtmlxScheduler的 JS 库中

I have read about the Razor syntax using @:and am currently using this method to send two string arrays. when trying to access these arrays in the JS function, they only appear to hold System.String[]

我已阅读有关 Razor 语法的使用, @:并且目前正在使用此方法发送两个字符串数组。在 JS 函数中尝试访问这些数组时,它们似乎只保留System.String[]

Here is the code:

这是代码:

var weekArray;
var engArray;

@foreach(var week in Model.WeeklySchedule)
{
    var key = week.Key;
    var values = week.Value.ToArray();
    var eng = Model.EngineerSchedule.Where(k => k.Key == key).Select(v => v.Value).ToArray();
    string test = "hello";

    @: gatherTimes('@values', '@eng');
}

function gatherTimes(values, engs)
{
    for(var i = 0; i < values.length; i++)
    {
        alert(values[i]);
    }

    //alert(values);
    //alert(engs);

    //weekArray[weekArray.length] = values;
    //engArray[engArray.length] = engineers;
}

I eventually plan on looping through the arrays, they hold information about time slots and engineer IDs. If there is any more information I may provide, I will do my best to do so.

我最终计划遍历数组,它们保存有关时间段和工程师 ID 的信息。如果我可以提供更多信息,我会尽力提供。

采纳答案by Strake

You will need to encode the list to JSON using JSON.Encode. Here is an example:

您需要使用 JSON.Encode 将列表编码为 JSON。下面是一个例子:

@{    
   // C# collection
   var collection= new List<string> {"A", "B", "C"};
 }

<script type="text/javascript"> 
   // encode C# collection to JSON, set to javascript variable
   var arr = @Html.Raw(Json.Encode(collection))
   for(var i = 0; i < arr.length; i++)
   {
      console.log(arr[i]); // Output is A  B  C
   }
</script>

In your case it would be like so:

在你的情况下,它会是这样的:

@: gatherTimes('@Html.Raw(Json.Encode(values))', '@Html.Raw(Json.Encode(eng))');