将数据存储到 ASP.NET MVC 3 控制器中的会话时出现 NullReferenceException
我在 ASP.NET MVC 3 控制器中有以下视图方法,该方法从 Amazon SimpleDb 检索数据,将其存储在列表中,然后将该列表对象存储在会话中。但是在我将 userBox 对象存储在会话中的行 (Session["userBox"] = userBox) 中,我收到 NullReferenceException。我确信 userBox 不为空。即使我尝试在会话中存储一个简单的字符串(例如 Session["userBox"] = "test"),我仍然会得到 NullReferenceException。
这是代码:
public ActionResult SetSidebarAccountBoxSessions(string id)
{
string selectExpression = "select * from MySimpleDBDomain where itemName()='" + id + "'";
SelectRequest sreq = new SelectRequest().WithSelectExpression(selectExpression);
SelectResponse sres = sdb.Select(sreq);
List<User> userBox = new List<User>();
if (sres.IsSetSelectResult())
{
SelectResult selectresult = sres.SelectResult;
foreach (Item item in selectresult.Item)
{
string a = item.Name;
userBox.Add(new User
{
imageThug = item.Attribute[0].Value,
name = item.Attribute[3].Value,
bio = item.Attribute[1].Value
});
}
}
Session["userBox"] = userBox;
return View();
}
我从另一个控制器方法调用此 SetSideBarAccountBoxSessions(id) 方法:
HomeController hc = new HomeController();
hc.SetSidebarAccountBoxSessions(item.Name);
这可能是问题吗?请帮忙。
I have a following View Method in an ASP.NET MVC 3 Controller that retrieves data from Amazon SimpleDb, stores it in a list and then stores that list object in a session. But at the line where I am storing the userBox object in a session (Session["userBox"] = userBox), I am getting a NullReferenceException. I am sure that userBox is not null. Even if I try to store a simple string in a session (like Session["userBox"] = "test") I still get NullReferenceException.
Here is the code:
public ActionResult SetSidebarAccountBoxSessions(string id)
{
string selectExpression = "select * from MySimpleDBDomain where itemName()='" + id + "'";
SelectRequest sreq = new SelectRequest().WithSelectExpression(selectExpression);
SelectResponse sres = sdb.Select(sreq);
List<User> userBox = new List<User>();
if (sres.IsSetSelectResult())
{
SelectResult selectresult = sres.SelectResult;
foreach (Item item in selectresult.Item)
{
string a = item.Name;
userBox.Add(new User
{
imageThug = item.Attribute[0].Value,
name = item.Attribute[3].Value,
bio = item.Attribute[1].Value
});
}
}
Session["userBox"] = userBox;
return View();
}
I am calling this SetSideBarAccountBoxSessions(id) method from another controller method:
HomeController hc = new HomeController();
hc.SetSidebarAccountBoxSessions(item.Name);
Can this be the problem? Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这个问题与您自己创建HomeController有关。您可以尝试使用
TransferToRouteResult
将操作传输到HomeController。您可以在此链接中找到
TransferToRouteResult
的代码:如何在ASP.NET MVC中模拟Server.Transfer?
I think this problem is related to the fact that you create HomeController by yourself. You can try to use
TransferToRouteResult
to transfer the action to HomeController.You an find the code of
TransferToRouteResult
in this link:How to simulate Server.Transfer in ASP.NET MVC?