简体   繁体   中英

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:

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:

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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