我正在寻找一种将 ViewDataDictionary 传递给 ASP.NET MVC 中的局部视图的方法,我得到了这种语法:
new ViewDataDictionary { { "Name", "Value" } }
我对这里的初始化语法有点困惑。谁能给我解释一下?
我正在寻找一种将 ViewDataDictionary 传递给 ASP.NET MVC 中的局部视图的方法,我得到了这种语法:
new ViewDataDictionary { { "Name", "Value" } }
我对这里的初始化语法有点困惑。谁能给我解释一下?
ViewDataDictionary
实现IDictionary<string, object>
。
IDictionary<string, object>
本质上是一个集合KeyValuePair<string, object>
。
您的ViewDataDictionary
初始化程序(外大括号)包含另一组表示KeyValuePair<string, object>
初始化程序的大括号。
这个答案解释了这可能的原因。
您可以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>
对象的好语法。
我使用扩展方法解决了这个问题:
/// <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 }))