Reputation: 12318
I would like to understand the order of how Razor engine execute the c# code started with @
.
I was trying to see the different times when the Controller is executed and the view is executed. So, I created this very simple ASP.NET MVC application. I store the time in a ViewBag
variable in the Controller and show it the View, I also show the current time in the view.
The controller have this:
public ActionResult Index()
{
ViewBag.ProcessingTime = DateTime.Now;
return View();
}
The view have this:
Processing time: @ViewBag.ProcessingTime<br />
@{
int i = 0;
do
{
i++;
<text>@i<br /></text>
}
while (i < 1000000);
}
Render time: @DateTime.Now
The result is something like this:
Processing time: 03/03/2012 04:16:48 p.m.
1
2
3
4
[...]
999998
999999
1000000
Render time: 03/03/2012 04:16:48 p.m.
Why if it's clearly taking time to show me the webpage while it executes the if
the ProcessingTime in the Controller and the RenderTime in the view is the same?
Upvotes: 0
Views: 1204
Reputation: 1038780
Remember that the page is rendered on the server. So even if it visually to you it appears very slowly on the client (because you are sending a huge HTML), the actual rendering happens on the server and probably this happens in less than a second as all you do is to loop over 1 million elements.
Try showing the processor ticks and you should notice a difference (and if you don't there must be something fundamentally wrong):
Processing time: @ViewBag.ProcessingTime.Ticks
... your loops and stuff
Render time: @DateTime.Now.Ticks
So the actual execution is the following:
/home/index
.Upvotes: 4