Code behind in ASP.NET MVC

前端 未结 6 617
长情又很酷
长情又很酷 2020-12-06 06:59

What is the purpose of the code behind view file in ASP.NET MVC besides setting of the generic parameter of ViewPage ?

6条回答
  •  时光说笑
    2020-12-06 07:40

    Ultimately, the question you ask yourself is this:

    Does this code A) Process, store, retrieve, perform operations on or analyze the data, or B) Help to display the data?

    If the answer is A, it belongs in your controller. If the answer is B, then it belongs in the view.

    If B, it ultimately becomes a question of style. If you have some rather long conditional operations for trying to figure out if you display something to the user, then you might hide those conditional operations in the code behind in a Property. Otherwise, it seems like most people drop the code in-line to the front end using the <% %> and <%= %> tags.

    Originally, I put all my display logic inside the <% %> tags. But recently I've taken to putting anything messy (such as a lengthy conditional) in my code behind to keep my XHML clean. The trick here is discipline - it's all too tempting to start writing business logic in the code behind, which is exactly what you should not be doing in MVC.

    If you're trying to move from traditional ASP.NET to ASP.NET MVC, you might aviod the code behinds until you have a feel for the practices (though it still doesn't stop you from putting business logic inside the <% %>.

提交回复
热议问题