Kayıtlar

Aralık 23, 2014 tarihine ait yayınlar gösteriliyor

Dynamic keyword in the asp.net views

Suppose you need to write a view that displays a list of Album instances. One possible approach is to simply add the albums to the view data dictionary (via the ViewBag property) and iterate over them from within the view. For example, the code in your Controller action might look like this: 1 2 3 4 5 6 7 8 public ActionResult List () { var albums = new List<Album>(); for ( int i = 0 ; i < 10 ; i++) { albums.Add( new Album {Title = "Product " + i}); } ViewBag.Albums = albums; return View (); } In your view, you can then iterate and display the products, as follows: 1 2 3 4 5 <ul> @foreach (Album a in (ViewBag.Albums as IEnumerable <Album> )) { <li> @a.Title </li> } </ul> Notice that we needed to cast ViewBag.Albums (which is dynamic) to an IEnumerable before enumerating it. We could have also used the dynamic keyword here to clean the view code up, but we would have lost the benefi t of IntelliSense when accessing the pr