I’m working on e-commerce site which is based on ASP.NET MVC3 with Razor Engine.
I want to display products.
for example,
only for 5 products.
@if (Model.Count > 0)
{
@foreach (var @item in Model)
{
<text>Product Name:</text>@item.Name
}
}
or
@if (Model.Count > 0)
{
<text>Product Name:</text>@Model.Name[0]
<text>Product Name:</text>@Model.Name[1]
<text>Product Name:</text>@Model.Name[2]
<text>Product Name:</text>@Model.Name[3]
<text>Product Name:</text>@Model.Name[4]
}
so which is best approach for fast rendering?
You are doing premature optimization which is something that you shouldn’t be doing. The second snippet will be negligibly faster than the first but, OMG, that’s ugly. I would prefer the code that’s most readable. And personally I would use a display template:
and then define a custom display template that will automatically be rendered for each element of the model (
~/Views/Shared/DisplayTemplates/MyViewModel.cshtml):