More generally, you are asking about the benefits of using a template rather than generating content directly inside your source code.
The answer is that mixing source code and HTML could be a viable alternative for small applications, but doesn't scale well. Once your project becomes large enough, it becomes too difficult to maintain code where chunks of HTML are all over the source code.
Using a template solves this issue. All your logic resides in controllers, while HTML is put in templates, which, in MVC, are called views. When someone wants to modify HTML, there is no need to deal with the business logic: only the view is affected. It might also work the other way around: you can swap the logic while letting HTML unchanged (as soon as the models remain the same).
So if templates are for HTML, what's all this source code in Razor?!
Indeed, you still need some logical statements within your templates, usually in a form of conditions or loops. If you need to display an avatar of a person only when the person actually has an avatar, well, that's a good place for an if
in your template. If you need to display every product which was provided by the controller through the model, there would be a foreach
.
The fact that you can write any code within your views doesn't mean you should. Be careful to keep business logic inside controllers. A few conditions and loops is fine, but if the code in your views becomes too complicate, it's a good sign that you've done too much. So:
All business logic should be in controllers (or business classes called by the controllers, depending on the N-tier architecture you use and the complexity of your application).
The models contain simple objects (usually POCO) which can be used easily, without too much code.
The views contain only the most elementary logic needed exclusively to generate HTML from the model. No complex business logic here.