What are dynamic properties?

Asked

Viewed 145 times

6

I am studying ASP.NET and saw the following code snippet:

ViewBag.QtdNovosComunicados =  
(from
   c in comunicados
 where
   c.DataCadastro > UsuarioLogado.dtUltimoAcesso
 select
c).Count();

I understand I’m creating a new property in the class ViewBag.

But how will it define this dynamic property? Does . NET do this at runtime? Type problems may occur when I access this property later?

1 answer

7


ViewBag is an object, not a class. It is a property of View which is used to mount the page.

Values are passed to the View at runtime, but this does not mean that they are weakly typed. If you try to use these values in ways that types do not allow, you will have exceptions. For example, the result of a call to Count() as in the example in the question is integer - if you try to call a method that integer does not possess, as Dispose(), you get a mistake.

Just one more thing: ViewBag is a very easy thing to use to commit abuse, and so its use is considered at best a code Smell (euphemism for small gambiarra), and at worst an anti-standard. The traditional way of passing data to the View is to complete these data in the Model, not in the ViewBag.

  • Oops, thank you for that very enlightening answer. In the case where we need to access data from more than one model in the view, as in reports, it is correct to use the viewBag object or would be the case of a Smell code as cited?

  • @Caiqueromero you can create a specific template for the Report View, which has the data filled out from other objects (which may include other templates). I suggest taking a look at composition in object orientation.

  • All right, I’ll search here, thanks again :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.