我正在寻找一种方法将ViewDataDictionary传递给ASP.NET MVC中的部分视图,我采用了这种语法:
new ViewDataDictionary { { "Name", "Value" } }
我对这里的初始化语法有点困惑。有人可以向我解释一下吗?
答案 0 :(得分:45)
ViewDataDictionary
实施IDictionary<string, object>
。
IDictionary<string, object>
基本上是KeyValuePair<string, object>
。
您的ViewDataDictionary
初始化程序(外部花括号)包含另一组花括号,表示KeyValuePair<string, object>
初始化程序。
this answer中解释了可行的原因。
您可以通过逗号分隔Add
初始值设定项来KeyValuePair<string, object>
多个项目:
var data = new ViewDataDictionary { { "Name", "Value" }, { "Name2", "Value2" } };
同样:
var data = new ViewDataDictionary
{
new KeyValuePair<string, object>("Name", "Value"),
new KeyValuePair<string, object>("Name2", "Value2")
};
基本上,内部花括号是初始化KeyValuePair<string, object>
对象的好语法。
答案 1 :(得分:4)
我使用扩展方法解决了这个问题:
/// <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;
}
和Html Helper扩展:
/// <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;
}
使用剃刀文件:
@Html.Partial("~/Some/Path.cshtml", Model, Html.vd(new { SomeKey = SomeObj }))