开发者

Should a view be dependent on its controller? (ASP.NET MVC)

开发者 https://www.devze.com 2022-12-10 17:24 出处:网络
Have a question about the design/usage of asp.net mvc here. In the html helper class, you can get to the current controller by Html.ViewContext.Controller.Moreover, you can get to the request, route

Have a question about the design/usage of asp.net mvc here.

In the html helper class, you can get to the current controller by Html.ViewContext.Controller. Moreover, you can get to the request, route collection and much more from the html helper class.

Doesn't this go against the rule of MVC? Doesn't this opens up a ways for developer to do heavy controller dependent code in views?

If not, what's the best practice use case for current viewcontext and controller from the html helper class?

Thanks in 开发者_如何学Goadvance.


Use a strong typed ViewModel, so your view is only dependant of it and not of the controller who generates it


Doesn't this go against the rule of MVC?

Yes, it goes.

Doesn't this opens up a ways for developer to do heavy controller dependent code in views?

Yes, it opens that door. It needs to be avoided.

what's the best practice use case for current viewcontext and controller from the html helper class?

The best practice is to write Html helpers unaware of controllers and contexts. They should do their job only based on what data is supplied by the caller.

There are however rare cases where you may want to stretch out of the box. For example, I wrote one a helper that would render Html elements and add automatically increasing IDs to them. In that case the helper should persists somewhere information about the previously used ID value. Here you may want to store that value in ViewContext, for example.

You should however only do such things when you clearly understand what and why you are doing this.


Simple answer is no, generally a view should not be dependant on a controller.

To elaborate a bit on what was already said; there are plenty of ways to shoot yourself in the foot using ASP.Net MVC if you're not careful. The basic concept helps, but there is no way to make it foolproof and still remain flexible enough to be considered useful.

You can do data access directly in the view without much trouble if you want to, or you can bind your model to the web session, etc. Like anything, you probably won't get it right the first time, but you will learn.

0

精彩评论

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