Kai
Kai

Reputation: 2073

ASP.NET MVC strongly typed views or not?

What is the best practice - to use only strongly typed views without any parameters, that passes through the ViewData dictionary, or it's a not bad idea to use something like this in a view:

<%: (string)ViewData["helloMessage"]%>

Thanks.

Upvotes: 3

Views: 1195

Answers (2)

Alexander Taran
Alexander Taran

Reputation: 6725

There is nothing wrong with using "magic strings"
But they are subject to typing errors.

In MVC 3 there is a dynamic object ViewModel in controller wich corresponds to a View object in view.
So you can assign ViewModel.MyData="something"; in controller and use it in your view as @View.MyData
It is kinda a better way to go.

Having only strongly typed views benefits from compile time checking.
And it is up to you to decide.
Personally I use dynamic object.

Upvotes: 1

Mariusz
Mariusz

Reputation: 1409

You should prefer strongly typed views. In some cases you need only one string like in your example, which doesn't belong to a model, then it is OK to use it. The other way is to encapsulate this variable into a class and pass the class to the view. The result would be a strongly typed view :-)

I personally don't like magical strings.

Upvotes: 6

Related Questions