Here's something very cool I just found in the ASP.NET MVC Preview 3 bits, you can specify, what I call, "dot" notation expressions on your view data. Say you had the following model:
1: public class Bar {
2: public int Id { get; set; }
3: public string Name { get; set; }
4: }
5:
6: public class Foo {
7: public int Id { get; set; }
8: public string Name { get; set; }
9: public Bar TheBar { get; set; }
10: }
When you define your view, you specify Foo as the type of your model. If you cared about type safety prior to run-time, you'd probably write your code in your view like:
<%= Html.Encode(ViewData.Model.TheBar.Name) %>
However, with the new ViewDataDictionary you can now use the "dot" notation expressions to get access the same. As you'll see, you're simply using the indexer of your ViewData object, which internally performs a data-binding eval like operation to search for the key. It is operating in a way that it first will access any specific ViewData items set within your controller, and if that is not found will attempt to perform an eval against your the Model. Using the following controller action:
1: public class FooController : Controller {
2: public ActionResult View() {
3: Foo foo = new Foo() { Id = 1,
4: Name = "My Foo",
5: TheBar = new Bar() {
6: Id = 12,
7: Name = "My Bar"
8: }
9: };
10: return View(foo);
11: }
12: }
You would write the following syntax in your view:
<%= Html.Encode(ViewData["TheBar.Name"]) %>
Given that you have not set the following,
ViewData["TheBar.Name"] = "My Bar";
within your code, you'll be surprised that this works like magic! However, if for any reason you do set the prior ViewData key in the controller action, it's value will be displayed instead of going to your model. Going even further, it doesn't necessarily always have to go off of your Model either, as
ViewData["FooObj"] = foo;
would allow you to access the members with the following expression within your view:
<%= Html.Encode(ViewData["FooObj.TheBar.Name"]) %>
Wow, super-powerful :) You gotta love that syntactical sugar!
06de7290-9dca-4ee0-9ed2-d7b50f16775d|1|4.0