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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:Repeaterthanforeachloop. 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 usingResponse.Writeinline 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.