javascript - How can I output the values in an array to a View in MVC with Razor? -
task
output values ienumerable of simple types in view.
conditions
i have model, passed in controller, contains array of simple values (in case int). want output variable in javascript block in view.
standards
without using large foreach block , iterating on each item , figuring out commas, output values in such way similar statement seen below.
example
var packagesummaryviewmodel = new packagesummaryviewmodel([1,2,3,4,5,6,7]); currently happening:
view.cshtml
var packagesummaryviewmodel = new packagesummaryviewmodel(@sensorids); output
var packagesummaryviewmodel = new packagesummaryviewmodel(system.int32[]);
the way use json serializer, json.net. json stands javascript object notation, it's natural use json serializer convert c#/.net objects javascript objects.
@using newtonsoft.json @model mynamespace.myobject var myproperty = @html.raw(jsonconvert.serializeobject(model.myproperty)); if model.myproperty list<int> containing integers 1, 2, 3, razor render follows:
var myproperty = [1,2,3]; if model.myproperty instance of following class
class c { public string x { get; set; } public double y { get; set; } } with x set apple , y set 0.5, razor render follows:
var myproperty = {"x":"apple","y":0.5}; the point same approach works json-serializable c#/.net object might passing model (or part of model).
Comments
Post a Comment