从MVC中的自定义视图模型在Razor页面上用JavaScript创建JSON对象数组?

时间:2021-08-01 17:01:18

I'm trying to populate the array in my script (it's going to be used for charting with D3.JS later on). According to this post, I'm supposed to use the syntax below. However, it doesn't work, bacause I get the error on the pushy line saying Uncaught ReferenceError: WebSite is not defined, where WebSite is the name of the namespace of the data (I'm guessing that, as it's the name of my project).

我正在尝试在我的脚本中填充数组(稍后将使用D3.JS进行制图)。根据这篇文章,我应该使用下面的语法。然而,它不起作用,因为我得到了关于Uncaught ReferenceError:未定义WebSite的错误线上的错误,其中WebSite是数据命名空间的名称(我猜这是因为它是我的名字)项目)。

<script>
  var data = new Array();
  @foreach (var piece in @Model.DataPieces)
  {
    @:data.push(@piece);
  }
</script>

I'm pretty sure it has to do with the data type of piece, because the following change makes it work (at least not producing a bunch of errors). I'm picking out the individual fields from piece object and push those into the array, as a new object.

我很确定它与片段的数据类型有关,因为以下更改使其工作(至少不产生一堆错误)。我从片段对象中挑出单个字段并将它们作为新对象推送到数组中。

<script>
  var data = new Array();
  @foreach (var piece in @Model.DataPieces)
  {
    @:data.push({'cat': '@piece.Category', 'key': '@piece.Key', 'val': '@piece.Value'});
  }
</script>

It's inconvenient, prone to mistakes and requires a refactoring of the assignment each time the model changes. How can I avoid this approach and be able to automagically create JSON objects upon assignment, as shown in the first sample?

它不方便,容易出错,并且每次模型更改时都需要重构赋值。我如何避免这种方法,并能够在分配时自动创建JSON对象,如第一个示例所示?

The viewmodel for the Razor page is declared as folows.

Razor页面的viewmodel声明为folows。

namespace WebSite.Models
{
  public class DrillDataViewModel
  {
    public List<DataPiece> DataPieces { get; set; }

    public class DataPiece
    {
      public string Category { get; set; }
      public string Key { get; set; }
      public int Value { get; set; }
    }
  }
}

3 个解决方案

#1


0  

Try to pass this from Razor page to JavaScript.

尝试将此从Razor页面传递给JavaScript。

@Html.Raw(@JsonConvert.SerializeObject(Model.DataPieces)
  .Replace("{\"", "{")
  .Replace(",\"", ",")
  .Replace("\":", ":"))

The replaces serve to get rid of the invalid characters produced by default in the converter without you needing to play with streams or applying other libraries. Ugly but working.

替换用于去除转换器中默认生成的无效字符,而无需使用流或应用其他库。丑陋但工作。

Sometimes, I also add one more replace: .Replace("\"","'") to get a more JS like look. The outer method is needed so you don't get problems with & in the &quote;.

有时,我还添加一个替换:.Replace(“\”“,”'“)以获得更像JS的外观。外部方法是必需的,因此您不会在&quote中出现问题。

This is a hand-on solution so if anybody knows a better way, I'd love to get some feedback.

这是一个实用的解决方案,所以如果有人知道更好的方式,我很乐意得到一些反馈。

#2


1  

The line @:data.push(@piece); will be written to the output HTML as

第@行:data.push(@piece);将输出HTML写为

data.push(<the result of calling ToString() on @piece>);

You need to replace @piece with something that will be evaluated to the JSON you want. This should work:

您需要将@piece替换为将要评估为您想要的JSON的内容。这应该工作:

@:data.push(@Html.Raw(Json.Encode(piece)));

Or you can just output the whole array at once:

或者你可以一次输出整个数组:

var data = @Html.Raw(Json.Encode(Model.DataPieces));

#3


0  

Try var yourJavascriptArray=@Html.Raw(Json.Encode(YouModel));

尝试var yourJavascriptArray=@Html.Raw(Json.Encode(YouModel));

#1


0  

Try to pass this from Razor page to JavaScript.

尝试将此从Razor页面传递给JavaScript。

@Html.Raw(@JsonConvert.SerializeObject(Model.DataPieces)
  .Replace("{\"", "{")
  .Replace(",\"", ",")
  .Replace("\":", ":"))

The replaces serve to get rid of the invalid characters produced by default in the converter without you needing to play with streams or applying other libraries. Ugly but working.

替换用于去除转换器中默认生成的无效字符,而无需使用流或应用其他库。丑陋但工作。

Sometimes, I also add one more replace: .Replace("\"","'") to get a more JS like look. The outer method is needed so you don't get problems with & in the &quote;.

有时,我还添加一个替换:.Replace(“\”“,”'“)以获得更像JS的外观。外部方法是必需的,因此您不会在&quote中出现问题。

This is a hand-on solution so if anybody knows a better way, I'd love to get some feedback.

这是一个实用的解决方案,所以如果有人知道更好的方式,我很乐意得到一些反馈。

#2


1  

The line @:data.push(@piece); will be written to the output HTML as

第@行:data.push(@piece);将输出HTML写为

data.push(<the result of calling ToString() on @piece>);

You need to replace @piece with something that will be evaluated to the JSON you want. This should work:

您需要将@piece替换为将要评估为您想要的JSON的内容。这应该工作:

@:data.push(@Html.Raw(Json.Encode(piece)));

Or you can just output the whole array at once:

或者你可以一次输出整个数组:

var data = @Html.Raw(Json.Encode(Model.DataPieces));

#3


0  

Try var yourJavascriptArray=@Html.Raw(Json.Encode(YouModel));

尝试var yourJavascriptArray=@Html.Raw(Json.Encode(YouModel));