asp.net-mvc - ASP.Net MVC Html.ActionLink() 问题

标签 asp.net-mvc routes

我正在使用 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 操作。整数?用于分页控件。我有两个 View ,一种称为“全部”,一种称为“详细信息”。我做错了什么?

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

关于asp.net-mvc - ASP.Net MVC Html.ActionLink() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/412412/

相关文章:

javascript - 通过 JavaScript 将 CSS 值传递给分部 View

asp.net-mvc - 为 asp.net mvc 应用程序托管 MS Windows Workflow 运行时的良好做法是什么?

asp.net-mvc - ActionResult 重定向使用 ToString() 呈现

javascript - 使用 $stateprovider 的 Angular $routeparams 为空

angular - Angular 7 中的中间件?

reactjs - 如何在 Reach Router 中使用不同的布局?

ruby-on-rails - Rails : No route matches . ..缺少必需的键:[:id]

c# - MVC 5 身份验证和 HttpClient 没有可用的 MediaTypeFormatter

.net - 为 Django/Pylons 程序员学习 C# 和 ASP.NET MVC

reactjs - NextJS 13 root.layout 在底部渲染 NavBar。有没有办法一致地将导航栏渲染在顶部?