我想在剃刀视图中创建一个表。
<div class="row" style="margin-left:80%">
@if (ViewBag.IsGlobal == 1)
{
<script>
$(document).ready(function () {
$("#btnViewLocal").prop("disabled",true);
@foreach (var item in Model.GlobalNewsModel)
{
var gTable = "<tr class=\"tvl\">";
gTable += "<td>";
gTable += "<input id=\"testid\" value=\"testvalue\" class=\"form-control\" />";
gTable += "<td>";
gTable += "</tr>";
//gTable.append("#wholeNews tr:last").after(gTable); <-- I tried it like this it also not working.
}
$("#WholeNews tr:last").after(gTable); // I can't place thisone inside foreach loop,it's unrecognize the $
});
</script>
}
}
</div>
我在没有foreach
循环的情况下对该表进行了硬编码并且它正在工作。但是我的要求是将其放在foreach循环中。为了您的参考,我已经把它放在这里。
var gTable = "<tr class=\"tvl\">";
gTable += "<td>";
gTable += '<input id="' + $(this).closest('tr').find('td :eq(0)').val() + "newsno" + '" disabled type="text\" class=\"form-control" value="' + $(this).closest('tr').find('td :eq(0)').val() + '">';
gTable += "</td>";
gTable += "</tr>";
$("#WholeNews tr:last").after(gTable);
答案 0 :(得分:1)
如何在客户端上创建循环:
@if (ViewBag.IsGlobal == 1)
{
<script>
$(document).ready(function () {
$("#btnViewLocal").prop("disabled", true);
// serialize the server side model on the client
var news = @Html.Raw(Json.Encode(Model.GlobalNewsModel));
// loop through the news javascript variable on the client
for (var i = 0; i < news.length; i++) {
// here you can access news[i] if you need to print
// some values from your model in the table
var gTable = "<tr class=\"tvl\">";
gTable += "<td>";
gTable += "<input id=\"testid\" value=\"testvalue\" class=\"form-control\" />";
gTable += "<td>";
gTable += "</tr>";
gTable.append("#wholeNews tr:last").after(gTable);
}
}
</script>
}
另请注意,如果您不需要访问客户端上的news[i]
,那么您可能不需要序列化您的模型,只需要长度:
var newsLength = @Model.GlobalNewsModel.Length;
for (var i = 0; i < newsLength; i++) {
...
}
但我想你需要模型值。另请注意,您只能在客户端上投影您真正需要的值,以避免在标记中浪费不必要的空间:
var news = @Html.Raw(Json.Encode(Model.GlobalNewsModel.Select(x => new
{
foo = x.Foo,
bar = x.Bar,
})));
for (var i = 0; i < news.length; i++) {
// you can access news[i].foo and news[i].bar here
...
}