2

我正在使用 MVC beta 编写一个简单的应用程序来理解 ASP.Net MVC。该应用程序是一个带有标签的简单照片/视频共享站点。我正在处理 MVC 骨架项目。我在导航栏中添加了一些 Html.ActionLink(),但是我在一个地方添加的 Html.ActionLink() 之一出现问题。

我希望 ~/Tags 显示数据库中的所有标签,我希望 ~/Tags/{tag} 显示所有带有 {tag} 标记的文件的列表。这按预期工作,但是当我关注 ~/Tags/{tag} 时,它会将导航栏中的 Html.ActionLink() 更改为与 ~/Tags/{tag} 链接相同,而不仅仅是指向 ~ /标签。我不明白为什么当我跟随 ~/Tags/{tag} 时导航栏中的 ActionLink() 会发生变化。如果我导航到项目中的其他链接,ActionLink() 将按预期工作。

我有这样的操作链接和路由设置。我的 TagsController 有这个 Index 动作。整数?用于分页控制。我有两个视图,一个称为全部,一个称为详细信息。我究竟做错了什么?

        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) 
        }
4

3 回答 3

4

我认为您需要处理 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);
}
于 2009-01-05T11:11:34.330 回答
2

除了像 Dan Atkinson 提到的那样创建额外的路由之外,您还应该摆脱控制器中的 if 语句,并创建另一个控制器方法(称为 Details)来处理标签详细信息。控制器中用于确定要显示哪个视图的 if 语句是代码异味。让路由引擎完成它的工作,您的控制器代码将更简单,更易于维护。

于 2009-01-05T14:08:26.390 回答
0

我建议你研究一下 Lamda 表达式来处理这个问题,你将来可能会得到一个“标签汤”。

此外,请确保您已下载 Microsoft.Web.Mvc dll,与 System.Web.Mvc 不同。

从哪里获得 Microsoft.Web.Mvc.dll

于 2009-01-05T12:02:27.907 回答