初始化程序语法:new ViewDataDictionary{{“名称”、“值”}}
本文关键字:程序 语法 名称 ViewDataDictionary 初始化 new | 更新日期: 2023-09-27 18:30:10
我正在寻找一种方法,将ViewDataDictionary传递到ASP.NET MVC中的部分视图,我得到了以下语法:
new ViewDataDictionary { { "Name", "Value" } }
我对这里的初始值设定项语法有点困惑。有人能给我解释一下吗?
ViewDataDictionary
实现IDictionary<string, object>
。
CCD_ 3本质上是CCD_。
ViewDataDictionary
初始值设定项(外部大括号)包含另一组表示KeyValuePair<string, object>
初始值设定值的大括号。
这个答案解释了这是可能的原因。
您可以通过逗号分隔KeyValuePair<string, object>
初始化程序来Add
多个项目:
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帮助程序扩展:
/// <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 }))