Razor MVC Populating Javascript array with Model Array

I'm trying to load a JavaScript array with an array from my model. Its seems to me that this should be possible.

Neither of the below ways work.

Cannot create a JavaScript loop and increment through Model Array with JavaScript variable

for(var j=0; j<255; j++)
{
jsArray = (@(Model.data[j])));
}

Cannot create a Razor loop, JavaScript is out of scope

@foreach(var d in Model.data)
{
jsArray = d;
}

I can get it to work with

var jsdata = @Html.Raw(Json.Encode(Model.data));

But I don't know why I should have to use JSON.

Also while at the moment I'm restricting this to 255 bytes. In the future it could run into many MBs.

130430 次浏览

这是可能的,你只需要循环通过剃须刀收集

<script type="text/javascript">


var myArray = [];


@foreach (var d in Model.data)
{
@:myArray.push("@d");
}


alert(myArray);


</script>

因此,就简洁性和速度而言,您自己的答案是最好的选择。

populating dropdown lists in my KnockoutJS model

var desktopGrpViewModel = {
availableComputeOfferings: ko.observableArray(@Html.Raw(JsonConvert.SerializeObject(ViewBag.ComputeOfferings))),
desktopGrpComputeOfferingSelected: ko.observable(),
};
ko.applyBindings(desktopGrpViewModel);

...

<select name="ComputeOffering" class="form-control valid" id="ComputeOffering" data-val="true"
data-bind="options: availableComputeOffering,
optionsText: 'Name',
optionsValue: 'Id',
value: desktopGrpComputeOfferingSelect,
optionsCaption: 'Choose...'">
</select>

注意,我使用 NET NuGet 包进行序列化,使用 ViewBag 传递数据。

我正在集成一个滑块,需要获得文件夹中的所有文件,并有相同的情况 C # 数组到 javascript 数组。@ heymega 提供的这个解决方案工作得非常完美,只是我的 javascript 解析器对 foreach循环中使用 var感到不满。所以我做了一些工作来避免循环。

var allowedExtensions = new string[] { ".jpg", ".jpeg", ".bmp", ".png", ".gif" };


var bannerImages = string.Join(",", Directory.GetFiles(Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "Images", "banners"), "*.*", SearchOption.TopDirectoryOnly)
.Where(d => allowedExtensions.Contains(Path.GetExtension(d).ToLower()))
.Select(d => string.Format("'{0}'", Path.GetFileName(d)))
.ToArray());

Javascript 代码是

var imagesArray = new Array(@Html.Raw(bannerImages));

Hope it helps

如果您想向数组中添加更复杂的项目,请展开最受欢迎的答案,以供参考:

@:myArray.push(ClassMember1: "@d.ClassMember1", ClassMember2: "@d.ClassMember2");

等等。

此外,如果希望将数组作为参数传递给控制器,可以首先对其进行字符串化:

Stringify ({‘ myArray’: myArray }) ;

I was working with a list of toasts (alert messages), List<Alert> from C# and needed it as JavaScript array for 烤面包机 in a partial view (.cshtml file). The JavaScript code below is what worked for me:

var toasts = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(alerts));
toasts.forEach(function (entry) {
var command = entry.AlertStyle;
var message = entry.Message;
if (command === "danger") { command = "error"; }
toastr[command](message);
});

如果它是一个对称的(矩形)数组,然后 尝试推入一个一维的 javascript 数组; 使用剃刀确定阵列结构; 然后转换成二维数组。

// this just sticks them all in a one dimension array of rows * cols
var myArray = new Array();
@foreach (var d in Model.ResultArray)
{
@:myArray.push("@d");
}


var MyA = new Array();


var rows = @Model.ResultArray.GetLength(0);
var cols = @Model.ResultArray.GetLength(1);


// now convert the single dimension array to 2 dimensions
var NewRow;
var myArrayPointer = 0;


for (rr = 0; rr < rows; rr++)
{
NewRow = new Array();
for ( cc = 0; cc < cols; cc++)
{
NewRow.push(myArray[myArrayPointer]);
myArrayPointer++;
}
MyA.push(NewRow);
}

这将是更好的方法,因为我已经实现:)

@model ObjectUser
@using System.Web.Script.Serialization
@{
var javaScriptSearilizer = new JavaScriptSerializer();
var searializedObject = javaScriptSearilizer.Serialize(Model);
}


<script>
var searializedObject = @Html.Raw(searializedObject )
console.log(searializedObject);
alert(searializedObject);
</script>

希望这将有助于您防止迭代模型(快乐编码)

具有命名字段的有效语法:

  var array = [];


@foreach (var item in model.List)
{
@:array.push({
"Project": "@item.Project",
"ProjectOrgUnit": "@item.ProjectOrgUnit"
});
}
<script>
var tempArray = [];


@foreach (var item in Model.Collection)
{
@:tempArray.push({ Field1: "@item.Field1", Field2: "@item.Field2" });
}


$("#btn").on("click", function () {
$.ajax({
url: '/controller/action',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(tempArray),
success: function (resp) {
alert(resp);
}
});
});
</script>

Controller/Action 参数: ICollection < _ Model > _ item

@functions
{
string GetStringArray()
{
var stringArray = "[";


for (int i = 0; i < Model.List.Count; i++)
{
if (i != Model.List.Count - 1)
{
stringArray += $"'{Model.List[i]}', ";
}
else
{
stringArray += $"'{Model.List[i]}']";
}
}


return stringArray;
}
}


<script>
var list = @Html.Raw(GetStringArray());
</script>

Maybe it could be interesting also this easy solution that can be easily applied also to javascript dictionaries:

<script type="text/javascript">
var myArray = [
@foreach (var d in Model.data)
{
@:"@d",
}
];
</script>

它可以转换为这个值(在这里,string1到 stringN 被认为是 Model.data 的内容)

<script type="text/javascript">
var myArray = [
"string1",
"string2",
"string3",
...
"stringN",
];
</script>