1

Task

Output the values from an IEnumerable of simple types in a view.

Conditions

I have a model, passed in by the controller, that contains an array of simple values (in this case int). I want to output it into a variable in a JavaScript block in the view.

Standards

Without using a large foreach block and iterating over each item and then figuring out the commas, output the values in such a way that is similar to the statement seen below.

Example

var packageSummaryViewModel = new PackageSummaryViewModel([1,2,3,4,5,6,7]);

Currently this is what is happening:

View.cshtml

var packageSummaryViewModel = new PackageSummaryViewModel(@sensorIds);

Output

var packageSummaryViewModel = new PackageSummaryViewModel(System.Int32[]);

1 Answer 1

7

The way I do this is to use a JSON serializer, like JSON.NET. JSON stands for JavaScript Object Notation, so it's natural to use a JSON serializer to convert C#/.NET objects to Javascript objects.

@using Newtonsoft.Json
@model MyNamespace.MyObject

var myProperty = @Html.Raw(JsonConvert.SerializeObject(Model.MyProperty));

If Model.MyProperty is a List<int> containing the integers 1, 2, 3, Razor will render this as follows:

var myProperty = [1,2,3];

If Model.MyProperty is an instance of the following class

class C
{
    public string X { get; set; }
    public double Y { get; set; }
}

with X set to apple and Y set to 0.5, Razor will render this as follows:

var myProperty = {"X":"apple","Y":0.5};

The point is that this same approach works for any JSON-serializable C#/.NET object you might be passing as your model (or part of your model).

Sign up to request clarification or add additional context in comments.

3 Comments

Well then why the heck did it take me 45 minutes to drag the below solution out of a bunch of guys who purport themselves to be MVC knowledgeable?
@CodeWarrior This is such an extremely common operation, rendering a C#/.NET object into a JS script as a literal. I can't speak to why it took them so long - maybe they still have some things to learn. :) Your guys did end up showing you how to render an IEnumerable<int> as JSON, but their solution is poor in that it implements JSON serialization in part. What if you want to serialize an IEnumerable<string>? A custom object? A Dictionary<int, List<string>>? Clearly you should be using a general-purpose JSON serializer for this purpose.
Indeed.I think I am going to delete my "answer" and vote yours up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.