简体   繁体   English

System.InvalidCastException:在ASP.NET MVC部分视图中

[英]System.InvalidCastException: in ASP.NET MVC partial views

In the controller: 在控制器中:

public ActionResult Index()
{
    ViewData["page"] = 0;
    return View(data);
}

public ActionResult More(long page = 0)
{
    ViewData["page"] = page;
    return View(data);
}

So, I have two views: Index.aspx and More.aspx. 因此,我有两个视图:Index.aspx和More.aspx。 I created a partial view (PartialView.ascx) that is used in both of the views. 我创建了在两个视图中都使用的局部视图(PartialView.ascx)。 Inside the partial view, it accessed both Model and ViewData. 在局部视图中,它访问了Model和ViewData。 The strange thing (to me anyway) is that when I tried to cast ViewData["page"] to a long, I would get the following casting exception for one of the views: 奇怪的是(无论如何对我来说)是,当我尝试将ViewData [“ page”]强制转换为一个很长的时间时,对于其中一个视图,我会得到以下强制转换异常:

System.InvalidCastException: Specified cast is not valid.

I tried to cast the ViewData["page"] like the following: 我试图将ViewData [“ page”]转换为如下所示:

if ((long) ViewData["page"] > 1) { ... }

and

long page = (long) ViewData["page"];
if (page > 1) { ... }

Each of them would throw a casting exception in one view of the other (but not both). 它们每个都会在另一个视图的一个视图中抛出强制转换异常(但不能同时出现)。

One difference between Index.aspx and More.aspx is that Index.aspx uses a master page, and More.aspx does not. Index.aspx和More.aspx之间的区别是Index.aspx使用母版页,而More.aspx不使用母版页。

Would anyone have any suggestion what may be wrong? 有人会提出什么建议吗? Please let me konw if I need to provide more details. 如果需要提供更多详细信息,请告诉我。 BTW, I'm farily new to C# and ASP.NET MVC. 顺便说一句,我是C#和ASP.NET MVC的新手。

This line: 这一行:

ViewData["page"] = 0;

is setting the value to be a boxed int . 将值设置为boxed int You're trying to unbox it to a long . 您正尝试将其拆箱到很long The simplest way to avoid this is to box to a long to start with: 避免这种情况的最简单方法是,将框框从很long距离开始:

ViewData["page"] = 0L;

... or use int for your page number to start with. ...或将int用作您的页码开头。 (Are you really going to get more than int.MaxValue pages?) (您真的会获得比int.MaxValue页面更多的int.MaxValue吗?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM