views:

23

answers:

1

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.

+2  A: 

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?)

Jon Skeet
Re. the type for page number, probably not. But I am getting this from a web service and I don't really have control over the type. :(Thanks for the suggestion. I'll try it out.
William
You must be joking....that *is* it! Cheers!
William