Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use C# code inline?

Tags:

c#

asp.net

I was once asked in an interview "What is the reason for using C# code inline in an aspx page". I couldn't answer, so I'm curious. Why would you do that instead of using code behind? Is there a technical reason?

like image 349
333Mhz Avatar asked Jul 28 '11 08:07

333Mhz


2 Answers

For ASP .NET WebForms

It is not a generally recommended practice to write inline code because WebForms make heavy use of “controls” that generate HTML output and presentation logic is expected to be handled by them. For example, to iterate over a data array you would rather use asp:Repeater than foreach loop. Using a loop in this case would smell bad and remind of classic ASP days when markup and code were mixed like a spaghetti. I can only think of using Response.Write inline to output debug messages.

For ASP .NET MVC

It's a totally different situation here. Because MVC discourages using “controls” in favor of clean, hand-coded HTML markup, inline code is the preferred way of generating HTML for model views. Of course, it also depends on what exactly you are doing in the inline code. My rule of thumb is use inline code when all data needed to render the view is made readily available by the controller. Inline code should only contain presentation logic, such as showing or hiding a field based on condition, getting a string from resources, enumerating over an array in the model, etc. You should never talk with the database from the view—this is what controller is for.

Some people don't feel comfortable using inline code in ASP .NET MVC because they have learned that “inline code is bad” when programming WebForms. This is a misconception, and my answer to it is inline code is only bad when it does something other than presentation logic. In WebForms this logic is handled by controls, in MVC—by the inline code, so there is no real problem here.

like image 120
Dan Abramov Avatar answered Oct 24 '22 02:10

Dan Abramov


I'd answer with the stereotypical "it depends"..

I would write inline C# (and frequently do) if it's a pure View concern. It's a common pattern with MVC applications to do complex display-related stuff by using simple C# in your views..

If the code in question strictly relates to rendering the data onto the page inline C# may very well be the simplest and easiest solution (unless you use WebForms where nothing is simple). If the code is not strictly related to rendering data I'd seperate the rendering part from the processing part and only use the rendering code in the view.

like image 30
Tigraine Avatar answered Oct 24 '22 03:10

Tigraine