代码之家  ›  专栏  ›  技术社区  ›  p.campbell

ASP.NET MVC:具有一个参数的操作方法未命名ID和非整数

  •  0
  • p.campbell  · 技术社区  · 16 年前

    考虑使用上面描述的区域约定的ASP.NET MVC 1.0项目 Nov. 2008 Phil Haack blog post . 这个解决方案一经设置就非常有效!

    由于我对ASP.NET MVC路由规则的了解有限,我的问题开始了。

    我的目的是创建这样的操作方法和URL结构:

    http://mysite/Animals/Dogs/ViewDog/Buster

    DogsController.ViewDog() 如下所示:

    public ActionResult ViewDog(string dogName)
    {
         if (dogName!= null)
         {
             var someDog = new DogFormViewModel(dogName); //snip a bunch more
    
             return View(someDog);
         }
         else { return View("DogNotFound"); }           
    }
    

    目前的任务是确保 RegisterRoutes() 有正确的条目。

    更新

    以下是正在映射的新路线:

    routes.MapRoute("ViewDog", "Animals/{controller}/{action}/{dogName}",
                                         new { controller = "Dogs", 
                                               action = "ViewDog", dogName = "" });
    

    创建指向URL的链接:

    <%= Html.RouteLink("Brown Buster", "ViewDog", new RouteValueDictionary(new { controller="Dogs", action="ViewDog", dogName="Buster" }))%>

    该URL按预期创建。多亏了 Craig Stuntz and his blog post on Html.RouteLink .

    http://mySite/Animals/Dogs/ViewDog/Buster

    新问题: 帕拉姆 dogName 不会从URL获取字符串值“buster”。对方法的调用成功,但参数的计算结果为空。

    问题

    你怎么能:

    • 使用字符串使此路由工作,并删除默认约定 int id 在路线上? 我想将参数的名称从 int .
    2 回复  |  直到 16 年前
        1
  •  1
  •   Craig Stuntz    16 年前

    您确定actionLink实际上与您向他们展示问题的路线匹配吗?当您有多个路由时,我强烈建议使用routelink而不是actionlink, as I explain in great detail in this post . 当您使用routelink时,您不可能匹配错误的路由,至少在URL生成中是这样。

        2
  •  0
  •   Chris    16 年前

    默认参数“id”不必是in t。它将匹配您在action方法中声明的任何类型。为什么不做下面的工作呢?

    public ActionResult ViewDog(string id)
    {
         if (id!= null)
         {
             var someDog = new DogFormViewModel(id); //snip a bunch more
    
             return View(someDog);
         }
         else { return View("DogNotFound"); }           
    }
    
    推荐文章