简体   繁体   中英

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. I created a partial view (PartialView.ascx) that is used in both of the views. Inside the partial view, it accessed both Model and 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:

System.InvalidCastException: Specified cast is not valid.

I tried to cast the ViewData["page"] like the following:

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.

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.

This line:

ViewData["page"] = 0;

is setting the value to be a boxed int . You're trying to unbox it to a long . The simplest way to avoid this is to box to a long to start with:

ViewData["page"] = 0L;

... or use int for your page number to start with. (Are you really going to get more than int.MaxValue pages?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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