简体   繁体   English

MVC5 将值列表传递给 jquery var

[英]MVC5 Pass list of values to jquery var

This is probably a beginner question but I can only find the other way round (from view back to the controller).这可能是一个初学者的问题,但我只能找到相反的方式(从视图返回到控制器)。

What I have is a ViewModel which contains the following property:我拥有的是一个 ViewModel,它包含以下属性:

public class MyViewModel {
    List<decimal> PossibleValues {get; set; }
}

I would now like to consume this list of values in a jquery variable inside my view:我现在想在我的视图中使用 jquery 变量中的值列表:

@model MyViewModel

<script>
    $(function() {

        var vals = @Model.PossibleValues;
        // should be var vals = [1.0, 2.0, 3.0];

    });
</script>

What is the "correct" way to pass this list of decimals into the jquery section.将此小数列表传递到 jquery 部分的“正确”方法是什么。 I can think of JSONfying the data or simply passing a string of preformatted values but I was wondering if there is a nicer way to do this?我可以考虑 JSONfying 数据或简单地传递一串预先格式化的值,但我想知道是否有更好的方法来做到这一点?

I wouldn't simply mix JavaScript in your cshtml files, as it can become a mess quite easily, it also depends on the type of data that comes in the model, one way of doing this is by using just the variables down in your cshtml pages in a script section, and then calling another script that lives on another place, therefore keeping stuff separate (HTML and JS) from each other.我不会简单地将 JavaScript 混合到您的 cshtml 文件中,因为它很容易变得一团糟,它还取决于 model 中的数据类型,一种方法是仅使用 cshtml 中的变量脚本部分中的页面,然后调用另一个位于另一个地方的脚本,因此将内容(HTML 和 JS)彼此分开。

Depending on how you want your data types, you could do the following:根据您想要的数据类型,您可以执行以下操作:

<script type="text/javascript">
    var vals = @Html.Raw(Json.Encode(Model.PossibleValues));
</script>

<script type="text/javascript" src="@Url.Content("~/rootFolder/js/yourjsfile.js")"></script>

You could also go to the console of your browser and type vals, also you could try only the Json.Encode and see the results, or only the Html.Raw to see what the outcome of your data would be like.您也可以 go 到您的浏览器控制台并输入 vals,您也可以只尝试 Json.Encode 并查看结果,或者只尝试 Z3135F4019BEE015E2D1ZAE7F77F9F3 来查看您的数据的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM