【问题标题】:Is this an ASP.NET MVC 2 Preview 1 bug, and what's the work-around?这是 ASP.NET MVC 2 Preview 1 的错误吗?有什么解决方法?
【发布时间】:2009-08-07 06:55:09
【问题描述】:

我在 ASP.NET MVC 2 预览版 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);
    }

当我使用有效的 URL 参数(例如“/Comment/List/22638”)时,我收到错误:

参数字典包含一个 参数输入无效 方法的“commentId” 'System.Web.Mvc.ActionResult 列表(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]'。 参数名称:参数

如果我将声明更改为:

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

代码运行良好。这是我做错了什么,还是反射对于 Int32 和 Int64 类型过于严格的问题?我能做些什么来解决它?将 long 转换为字符串?

【问题讨论】:

  • 这在 MVC1 中对我有用。你能重现 MVC1 中的错误吗?
  • 还没有尝试过 MVC 1 .. 因为这是一个新项目,我正在“展望未来”并且非常享受新模板的支持,我不想回到 MVC 1 . 这是让 MVC 对我更有吸引力的版本 :)
  • 我的意思是,我还没有在 MVC 1 中测试过这个。

标签: asp.net-mvc dictionary parameters preview


【解决方案1】:

我认为这更具可读性/不那么混乱,并且也适用于 MVC 1:

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

【讨论】:

  • 感谢克雷格(和斯宾塞)。我还需要更新我的路由以支持第二个 ID,我现在可以使用它了。
【解决方案2】:

试试

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

【讨论】:

  • 方便的简写:[DefaultValue(0L)]
【解决方案3】:

只需将以下内容添加到 global.asax Application_Start 方法中

ModelMetadataProviders.Current = new DataAnnotationsModelMetadataProvider();

有关这方面的更多信息,请参阅 Scott 的博客:http://weblogs.asp.net/scottgu/archive/2010/12/14/update-on-asp-net-mvc-3-rc2-and-a-workaround-for-a-bug-in-it.aspx

另见jQuery Sort and MVC Stopped Working

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2023-03-29
    • 2019-05-24
    • 1970-01-01
    相关资源
    最近更新 更多