ASP.NET - Inline vs. Code-Behind

随声附和 提交于 2019-12-22 06:01:11

问题


I realize that by asking this question, I could have started the apocalypse, but a colleague of mine uses a lot of inline coding in their aspx pages, where as I prefer using the code-behind.

Is there a right and a wrong way here?


回答1:


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.




回答2:


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




回答3:


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");.




回答4:


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.




回答5:


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.




回答6:


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">




回答7:


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.




回答8:


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.



来源:https://stackoverflow.com/questions/1201418/asp-net-inline-vs-code-behind

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