Search code examples
asp.net-mvcdictionaryparameterspreview

Is this an ASP.NET MVC 2 Preview 1 bug, and what's the work-around?


I'm using this code in ASP.NET MVC 2 preview 1:

    public ActionResult List(long id, [DefaultValue(0)] long? commentId)
    {
        var model = UserComment.ForRefId(id);
        PageTitle = string.Format("Comments for '{0}'", 
                                  SetCommentThread(id).Subject);
        ViewData[MvcApplication.SAnchor] = commentId;
        return View("List", model);
    }

When I use a valid URL argument such as "/Comment/List/22638", I get the error:

The parameters dictionary contains an invalid entry for parameter 'commentId' for method 'System.Web.Mvc.ActionResult List(Int64, System.Nullable1[System.Int64])' in 'ThreadsMVC.Controllers.CommentController'. The dictionary contains a value of type 'System.Int32', but the parameter requires a value of type 'System.Nullable1[System.Int64]'. Parameter name: parameters

If I change the declaration to:

    public ActionResult List(long id, [DefaultValue(0)] int? commentId)

The code runs fine. Is this something I'm doing wrong, or a problem with the reflection being too type strict for Int32 vs Int64? And what can I do to fix it? Cast the long as a string?


Solution

  • I think this is more readable/less messy, and works in MVC 1, too:

    public ActionResult List(long id, long? commentId)
    {
        var model = UserComment.ForRefId(id);
        PageTitle = string.Format("Comments for '{0}'", 
                                  SetCommentThread(id).Subject);
        ViewData[MvcApplication.SAnchor] = commentId.GetValueOrDefault(0);