最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I output the values in an array to a View in MVC with Razor? - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 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).

发布评论

评论列表(0)

  1. 暂无评论