Reputation: 4560
I want to create a table inside razor view.
<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>
I hardcoded that table without foreach
loop and it's working.But my requirement is to put that one in inside foreach loop.for your reference i've put that one here.
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);
Upvotes: 0
Views: 666
Reputation: 1038790
How about making the loop on the client:
@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>
}
Also note that if you don't need to access news[i]
on the client then you probably don't need to serialize your model, all you need is the length:
var newsLength = @Model.GlobalNewsModel.Length;
for (var i = 0; i < newsLength; i++) {
...
}
but I guess you need the model values. Also notice that you can project only the values that you really need on the client to avoid wasting unnecessary space in the markup:
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
...
}
Upvotes: 1