Type Safety With ViewData

Given the following action:
public ActionResult IndexViewData()
{
	DummyViewData[] testArray = new DummyViewData[] { new DummyViewData(){ Value1 = 1, Value2 = 2 }, new DummyViewData(){ Value1 = 3, Value2 = 4 }
		, new DummyViewData(){ Value1 = 5, Value2 = 6 } };

	//We can't pass in the array directly because there is no new() method for a typed array
	ViewData["TestArray"] = new List<DummyViewData>(testArray);

	return View(GetTestProduct());
}

And the following model:
namespace MvcImprovedTest.Models
{
	public class DummyViewData
	{
		public long Value1;
		public long Value2;
	}
}

We can create the following type-safe repeater:
<%@ Page Language="C#" Inherits="MvcImproved.Generic.ViewPage" ModelType="MvcImprovedTest.Models.Product" MasterPageFile="~/Views/Shared/Site.Master"%>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Accessing ViewData</h2>

	<mvcg:Repeater runat="server" ModelType="System.Collections.Generic.List`1[[MvcImprovedTest.Models.DummyViewData, MvcImprovedTest]]" DataKey="TestArray">
		<ItemTemplate>
			<span><mvcg:Literal runat="server" ValueMember="Value1" /></span>
		</ItemTemplate>
	</mvcg:Repeater>

</asp:Content>

DefaultModelBinderImproved

Given the following model:
namespace MvcImprovedTest.Models
{
	public class DummyViewData
	{
		public long Value1;
		public long Value2;
	}
}

And the following HTML form:
<input type="hidden" name="d[4].Value1" value="1" />
<input type="hidden" name="d[4].Value2" value="2" />
<input type="hidden" name="d[5].Value1" value="3" />
<input type="hidden" name="d[5].Value2" value="4" />

The following Action will correctly have 2 DummyViewData elements:
public ActionResult Index(List<DummyViewData> list)
{ }

You can also use a Dictionary<>:
<input type="hidden" name="d[foo].Value1" value="1" />
<input type="hidden" name="d[foo].Value2" value="2" />
<input type="hidden" name="d[bar].Value1" value="3" />
<input type="hidden" name="d[bar].Value2" value="4" />

The following dictionary parameter would have 2 Key,Value pairs, with one key being "foo" and the other "bar"
public ActionResult Index(Dictionary<string, DummyViewData> dictionary)
{ }

Last edited Aug 17, 2009 at 11:42 PM by marquinhocb, version 9

Comments

No comments yet.