ASP.NET - Inline vs. Code-Behind

跟風遠走 提交于 2019-12-05 09:04:28

Not unless your coding standard says otherwise.

IMO code-behind helps separation of concerns, so I prefer that, but sometimes just dealing with one file is nice too.

Code-behind is the more traditional and logical place. If it works, it works, but I can't stand doing it in the aspx.

Kelsey

I made the exact post a while back:

OnDataBinding vs Inline: pros, cons and overhead

I prefer the code behind. I usually have a #region area for all the databinding stuff. It allows for people skilled in HTML / CSS to tweak the HTML and all they have to know is what basic controls to use and to define the OnDataBinding event in the control's definition. They can move things around and do whatever and have no knowledge of what it actually takes to get the data into that databind as it might not be as simple as just a basic 'Eval("something");.

Well, there's inline code, and then there's inline code. If you have a script block at the top for you page_load, that's just fine. But if you're mixing a lot of bee-stings (<% %>) in with the markup, you'll eventually start to have trouble when those bee-stings don't work as you would like with other server controls.

Personally I prefer compile errors to run-time errors so I put all my logic in code behinds.

Occasionally when I just need a value to show up on the page I'll put <%=SomeValue%> but even then I much prefer to create a label and set it.

I want to make sure i understand the question - by in-line, do you mean snippets like

<a><% some.asp.net.code %></a>

or do you mean one vs. two files for each page:

page.aspx
page.aspx.cs

?

Because I am NOT a fan of what I call the 'embedded' code in the first example but I DO prefer code and markup in the same file with a < script runat="server">

There is no right/wrong with either of this.

You can write some code inline & some of it should be written in code-behind. It can't be absolute. Depends on how readable/maintainable it becomes when you write it on the other side.

EDIT: As it is said, write code for human & incidentally for the compiler.

I tend to use the code-behind since it is the only way for WPF and I try to stay consistant and it feels more natural. But thats subjective.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!