Should it depend on its controller? (ASP.NET MVC)

You have a question about the design / use of asp.net mvc here.

In the html helper class, you can navigate to the current controller using Html.ViewContext.Controller. In addition, you can get a request, route collection, and much more from the html helper class.

Isn't that against the MVC rule? Doesn't this open the way for the developer to make heavy controller-dependent code in views?

If not, what is the best use for the current viewcontext and controller from the html helper class?

Thanks in advance.

+4
source share
3 answers

Use a strong typed ViewModel, so your view depends only on it, and not on the controller that generates it.

+8
source

Isn't that against the MVC rule?

Yes, this is happening.

Doesn't this open up the possibility for developers to make heavy controller-dependent code in views?

Yes, he opens this door. This should be avoided.

What is the best use case for the current viewcontext and controller from the html helper class?

Best practice is that the HTML helpers are not aware of controllers and contexts. They should do their work only on the basis of what data is provided by the caller.

However, there are rare cases where you can stretch out of the box. For example, I wrote one helper that will display HTML elements and add automatically increasing identifiers to them. In this case, the assistant must store information about the previously used identifier value. Here you might want to store this value in a ViewContext, for example.

However, you should only do such things when you clearly understand what and why you are doing it.

+4
source

The simple answer is no, usually the view should not depend on the controller.

To tell a little about what has already been said; There are many ways to shoot in the leg using ASP.Net MVC if you are not careful. The basic concept helps, but there is no way to make it reliable and still remain flexible enough to be considered useful.

You can access data directly in the view without any problems if you want, or you can bind your model to a web session, etc. Like everyone, you probably won't be right the first time, but you will be taught.

0
source

All Articles