【问题标题】:How to get a dictionary from Controller?如何从控制器中获取字典?
【发布时间】:2019-11-20 00:14:37
【问题描述】:

我有三门课。第一个类调用Data 类的AddInfo 方法。然后 Data 类实例化字典。最后,控制器类调用 getDictionary 方法。 它给了我一个错误:KeyNotFoundException: The given key 'info' was not present in the dictionary.

HomeController.cs

public IActionResult Index()
{
    Data d = new Data();
    var getDic = d.getDictionary();

    var Info = getDic["First"];

    return View(Info);
}

数据.cs

public interface IData 
{
     Dictionary<string, object> getDictionary();
     void AddInfo(string infoName, TheObject obj);
}

public class Data : IData 
{
    public Dictionary<string, object> infoList;

    public Data()
    {
        infoList = new Dictionary<string, object>();
    }

    public Dictionary<string, object> getDictionary()
    {
        return this.infoList;
    }

    public void AddInfo(string infoName, TheObject obj)
    {
        infoList.Add(infoName, obj);
    }
}

【问题讨论】:

  • 哪一行是发生错误的那一行?您可以发布将对象添加到Data 类的代码吗?
  • @howcheng 错误发生在“var Info = getDic["First"];"看起来字典在添加信息之前被调用。

标签: c# asp.net-mvc dictionary asp.net-core


【解决方案1】:

您的“数据”对象引用是在您的 HomeController 类中的这一行中创建的:

Data d = new Data();

然后您几乎立即尝试在以下行访问它:

var Info = getDic["First"];

您绝不会拨打d.AddInfo("first", testObject) 或类似电话。
如果您在其他地方有另一个 Data 类的实例,请记住它们是两个完全独立的对象,因此不共享同一个字典。

如果您在更高的其他地方创建了 Data 类的实例,那么可能的解决方案可能是您需要将其传递给 Index 方法,如下所示:

public IActionResult Index(IData d)
{
    var getDic = d.getDictionary();

    var Info = getDic["First"];

    return View(Info);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多