What exactly is ViewUserControl.ViewDataKey?

280 views Asked by At

The documentation doesn't say much. http://msdn.microsoft.com/en-us/library/system.web.mvc.viewusercontrol.viewdatakey(v=vs.98).aspx

What is the purpose of the ViewDataKey property of ViewUserControl and how can it be leveraged?

1

There are 1 answers

2
patmortech On BEST ANSWER

The ViewDataKey property can be used to specify the key of the item in the ViewData collection that you want to use for the ViewUserControl's Model. Basically, instead of just inheriting the parent's entire ViewData collection by default, the control will just get the item with the key you specify.

So, for example, if you put ViewDataKey="EmployeeData", then it would look for an item in ViewData with the key "EmployeeData", and it would use that as the Model object for your ViewUserControl.

From what I can see, this is mainly used when using a declarative syntax for putting ViewUserControls inside a view. Meaning, instead of using RenderPartial, you use the old WebForm's syntax for registering a user control on a page, and have a server tag like <MyApp:MyUserControl runat="server" ViewDataKey="EmployeeData" />.