开发者

In .Net MVC, Is it considered bad practice to access session information from View?

开发者 https://www.devze.com 2022-12-14 22:06 出处:网络
I recently ran into a situation in which accessing session information from view is the most intuitive and quick solution to the problem. So, I just did it without thinking too much. But now when I re

I recently ran into a situation in which accessing session information from view is the most intuitive and quick solution to the problem. So, I just did it without thinking too much. But now when I revisit my code. I somehow feel uncomfortable about the decision I made earlier. I can't clear state what is wrong of doing what I did. Just a "hinch" telling me I shouldn't do this.

Shoul开发者_如何学Cd I replace my code with ViewData or TempData? This will require adding a few lines of code. Or should I just leave things as is, because "it's not broken"?


My preference would be copy the data in your controller method to the ViewData or the model itself. That really is more the responsibility of the controller, as opposed to the view.

I don't think it's officially considered a bad practice, but I could see it leading to maintenance headaches later on. You don't really want your views to be tied to external state; they should only be tied to the model/viewmodel/viewdata.


You're not a freak at all. In fact, I'm a militant refactorer when it comes to cleaning things up. For future reference, it's generally best practices to keep heavy logic out of your views. They say you're suppose to have very skinny/dumb views, controllers that do minor bits of logic and play traffic cop, and models that handle all the deep stuff.

I do everything in my power to limit my view logic to simple operations on the ViewModel and ViewData. I also use custom HtmlHelpers, RenderPartials, and RenderActions to keep my views skinny and uncomplicated.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号