代码之家  ›  专栏  ›  技术社区  ›  Ben Robbins

ASP.NET MVC HTML.ActionLink()问题

  •  2
  • Ben Robbins  · 技术社区  · 16 年前

    我正在使用MVC测试版编写一个简单的应用程序来理解ASP.NET MVC。该应用程序是一个带有标签的简单照片/视频共享网站。我正在进行MVC框架项目。我在导航栏中添加了一些html.actionlink(),但是我在一个地方添加了一个html.actionlink()有问题。

    我希望~/tags显示数据库中的所有标记,我希望~/tags/tag显示标记了tag的所有文件的列表。这按预期工作,但当我使用~/tags/标记时,它会将导航栏中的html.actionlink()更改为与~/tags/标记链接相同,而不是只指向~/tags。我不明白为什么当我跟随~/tags/tag时,导航栏中的actionLink()会发生变化。如果我导航到项目中的其他链接,actionLink()将按预期工作。

    我有这样的行动链接和路线。我的TagsController有这个索引操作。int?用于分页控件。我有两种观点,一种叫“全部”,另一种叫“细节”。我做错什么了?

            Html.ActionLink("Tags", "Index", "Tags") // In navigation bar
    
            routes.MapRoute(
                "Tags",
                "Tags/{tag}",
                new
                {
                  controller = "Tags", action = "Index", tag = "",
                });
    
            public ActionResult Index(string tag, int? id )
            {  // short pseudocode
               If (tag == "")
                 return View("All", model)
               else
                 return View("Details", model) 
            }
    
    3 回复  |  直到 14 年前
        1
  •  4
  •   Dan Atkinson    14 年前

    我认为您需要处理yoursite.com/tags/的一个实例,因为您只处理一个带有标记的实例。

    我会创建另一条路线:

    routes.MapRoute(
      "TagsIndex", //Called something different to prevent a conflict with your other route
      "Tags/",
      new { controller = "Tags", action = "Index" }
    );
    
    routes.MapRoute(
      "Tags",
      "Tags/{tag}",
      new { controller = "Tags", action = "Tag", tag = "" }
    );
    
    
    /* In your controller */
    public ActionResult Index() // You could add in the id, if you're doing paging here
    {
      return View("All", model);
    }
    
    public ActionResult Tag(string tag, int? id)
    {
      if (string.IsNullOrEmpty(tag))
      {
        return RedirectToAction("Index");
      }
    
      return View("Details", model);
    }
    
        2
  •  2
  •   John Sheehan    16 年前

    除了像DanAtkinson提到的那样创建一个额外的路由之外,您还应该去掉控制器中的if语句,并创建另一个控制器方法(称为details)来处理标记细节。如果控制器中的语句确定要显示的视图是代码气味。让路由引擎完成它的工作,您的控制器代码将更简单,更容易维护。

        3
  •  0
  •   Community PPrice    7 年前

    我建议你研究一下lamda的表达方式来解决这个问题,将来你可能会得到一个“标签汤”。

    此外,请确保您下载了与system.web.mvc不同的microsoft.web.mvc dll。

    Where to get Microsoft.Web.Mvc.dll