3

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.

Kai
  • 2,023
  • 7
  • 28
  • 49

2 Answers2

6

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.

Sam Holder
  • 32,535
  • 13
  • 101
  • 181
Mariusz
  • 1,409
  • 12
  • 25
  • 1
    If you're only passing a string to the View, you don't need to create a special class just for the string. Instead, pass the string class itself as the model: `string a = ""; return View(a);` Also, if it's a string, you'd have to do `return View((object)a);` so that the string isn't confused for the View name - however, you can keep the View pointing to a string model. – Maxim Zaslavsky Nov 29 '10 at 18:45
1

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.

AlexB
  • 7,302
  • 12
  • 56
  • 74
Alexander Taran
  • 6,655
  • 2
  • 39
  • 60