开发者

System.InvalidCastException: in ASP.NET MVC partial views

开发者 https://www.devze.com 2023-01-10 06:11 出处:网络
In the controller: public ActionResult Index() { ViewData[\"page\"] = 0; return View(data); } public ActionResult More(long page = 0)

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号