<div class="container_cards">
@foreach (var card in ViewBag.Cards)
{
<div>
<div>
<a href="cards/@card.url">
<img src="@card.img">
</a>
</div>
<div>
<a href="cards/@card.url">
<h2>@card.title</h2>
<h3>@card.definition</h3>
</a>
<div>
<div>@card.author</div>
<div>@card.month/@card.day/@card.year</div>
</div>
</div>
</div>
}
</div>
I have a code block like this in my cshtml file. It is filled with required information when C# controller function fills the ViewBag.Cards.
But I have pagination. I need to show next 5 cards when I press a next button. I call an AJAX function from JS file and get the next 5 cards information as a JSON string. I replace the current page with the new page with a code as follows:
function change_page(response) {
var buf = "";
var responseObject = JSON.parse(response);
for (var i = 0; i < responseObject.length; i++) {
buf += `<div>
<div>
<a href="/cards/${responseObject[i].url}">
<img src="${responseObject[i].img}">
</a>
</div>
<div>
<a href="/cards/${responseObject[i].url}">
<h2>${responseObject[i].title}</h2>
<h3>${responseObject[i].definition}</h3>
</a>
<div>
<div>${responseObject[i].author}</div>
<div>${responseObject[i].month}/${responseObject[i].day}/${responseObject[i].year}</div>
</div>`;
buf += `</div></div></div>`;
}
$(".container_cards").html(buf);
}
I concatenate HTML codes into a string and replace it with current HTML codes. It looks ugly and I wonder if there is a more elegant and efficient way to achieve this, maybe with making use of razor?
I am using ASP.Net 5 by the way.