'Initializer syntax: new ViewDataDictionary { { "Name", "Value" } }
I was searching for a way to pass ViewDataDictionary to a partial view in ASP.NET MVC that I came to this syntax:
new ViewDataDictionary { { "Name", "Value" } }
I'm a bit confused about the initializer syntax here. can anyone explain it to me?
Solution 1:[1]
I solved this using an extension method:
/// <summary>
/// Use this extension method to create a dictionary or objects
/// keyed by their property name from a given container object
/// </summary>
/// <param name="o">Anonymous name value pair object</param>
/// <returns></returns>
public static Dictionary<string, object> ToDictionary(this object o)
{
var dictionary = new Dictionary<string, object>();
foreach (var propertyInfo in o.GetType().GetProperties())
{
if (propertyInfo.GetIndexParameters().Length == 0)
{
dictionary.Add(propertyInfo.Name, propertyInfo.GetValue(o, null));
}
}
return dictionary;
}
And an Html Helper extension:
/// <summary>
/// When viewData is null, we just return null. Otherwise, we
/// convert the viewData collection to a ViewDataDictionary
/// </summary>
/// <param name="htmlHelper">HtmlHelper provided by view</param>
/// <param name="viewData">Anonymous view data object</param>
/// <returns></returns>
public static ViewDataDictionary vd(this HtmlHelper htmlHelper, object viewData)
{
if (viewData == null) return null;
IDictionary<string, object> dict = viewData.ToDictionary();
//We build the ViewDataDictionary from scratch, because the
// object parameter constructor for ViewDataDictionary doesn't
// seem to work...
ViewDataDictionary vd = new ViewDataDictionary();
foreach (var item in dict)
{
vd[item.Key] = item.Value;
}
return vd;
}
Use from a razor file as:
@Html.Partial("~/Some/Path.cshtml", Model, Html.vd(new { SomeKey = SomeObj }))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fordareh |
