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 mas, 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[]);
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 mas, 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[]);
Share
Improve this question
asked Jun 7, 2014 at 22:40
CodeWarriorCodeWarrior
7,4687 gold badges54 silver badges79 bronze badges
1 Answer
Reset to default 7The 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).