ASP.NET MVC Beta - Setting properties on ViewControls
In ASP.NET MVC Beta, it isn’t possible to set properties on partials when calling them with Html.RenderPartial.
Rusty Zarse blogged about a useful ViewData helper class, which allows you to set properties by passing values to the partial through the ViewData.
I’ve extended this slightly to enable the following syntax:
1 2 3 4 5 6 7 8 | <% Html.RenderPartial("YUIDataTable", ViewDataDictionaryBuilder.Create( new { DataTableId = "QuoteDataTable", ConfigNamespace = "QuoteDataTableConfig", HideFilter = true }));%> |
Which sets properties on a ViewUserControl like this:
1 2 3 4 5 6 7 8 9 10 11 | public partial class YUIDataTable : ViewUserControl { public string ConfigNamespace { get; set; } public string DataTableId { get; set; } public bool HideFilter { get; set; } protected void Page_Load(object sender, EventArgs e) { ViewDataDictionaryBuilder.SetPropertiesToViewDataValues(this); } } |
Here is the full helper code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | using System; namespace MvcHelpers { /// /// With thanks to http://www.vitaminzproductions.com/technology-blog/index.php/2008/11/12/setting-properties-using-aspnet-mvc/ /// public static class ViewDataDictionaryBuilder { public static System.Web.Mvc.ViewDataDictionary Create(object data, ModelType model) where ModelType : class { return (System.Web.Mvc.ViewDataDictionary)CreateInternal(new System.Web.Mvc.ViewDataDictionary(model), data); } public static System.Web.Mvc.ViewDataDictionary Create(object data, object model) { return CreateInternal(new System.Web.Mvc.ViewDataDictionary(model), data); } public static System.Web.Mvc.ViewDataDictionary Create(object data) { return CreateInternal(new System.Web.Mvc.ViewDataDictionary(), data); } private static System.Web.Mvc.ViewDataDictionary CreateInternal(System.Web.Mvc.ViewDataDictionary dictionary, object data) { AddPropertiesToViewData(dictionary, data); return dictionary; } private static void AddPropertiesToViewData(System.Web.Mvc.ViewDataDictionary dictionary, object data) { if (data == null) return; System.Reflection.PropertyInfo[] properties = data.GetType().GetProperties(); foreach (var property in properties) { dictionary.Add(property.Name, property.GetValue(data, null)); } } public static void SetPropertiesToViewDataValues(System.Web.Mvc.ViewUserControl viewUserControl) { foreach (var property in viewUserControl.GetType().GetProperties()) { if (viewUserControl.ViewData[property.Name] != null) property.SetValue(viewUserControl, Convert.ChangeType(viewUserControl.ViewData[property.Name], property.PropertyType), null); } } } } |
Hope that’s useful to you!





