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

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

我有像这样设置的actionlink和路线。我的TagsController有这个Index动作。 int?用于寻呼控制。我有两个视图,一个叫All,一个叫Details。我做错了什么?

        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) 
        }
有帮助吗?

解决方案

我认为您需要处理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);
}

其他提示

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

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

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top