【问题标题】:How to get the add the query string to actionLink?如何将查询字符串添加到 actionLink?
【发布时间】:2019-04-02 16:29:09
【问题描述】:

以下链接为以下网址:http://localhost:11111/files/Details/3

  @Html.ActionLink("Details", "Details", "mycontroller", new { id = item.id },null)

但我正在尝试使用像 http://localhost:11111/files/Details?id=3http://localhost:11111/files/Details.aspx?id=3 这样的 url 参数

如何获取操作链接以显示详细信息之类的 url?i=3

这是我的控制器视图:

public ActionResult Details(int? id)
    {
       ...
        return View();
    }

【问题讨论】:

  • 有什么问题?当您尝试使用示例链接时遇到什么错误?请在请求帮助时更具体地说明当前行为。

标签: asp.net-mvc razor


【解决方案1】:

路由代码可以在我们项目的Global.asax文件的RegisterRoutes方法下找到。

我在 RegisterRoutes 方法中看到了一个 cookie。

routes.MapRoute(
 "Default",     // Route name
 "{controller}/{action}/{id}",     // URL with parameters
 new { controller = "Home", action = "Index", id = "" }    // Parameter defaults);

使用上面的 MapRoute 方法,我们定义了一条新路线。

示例;

public class HaberController : Controller
{
      public ActionResult Listele()
      {
           // Listing codes will be written
            return View("Listele");
      }

      public ActionResult Detay(string HaberId)
      {
           // Detail codes will be written
           return View("Detay");
      }
}

我们转到 Global.asax 文件并按如下方式对其进行编辑。

public static void RegisterRoutes(RouteCollection routes)
{
       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

       routes.MapRoute(
             "HaberListeleme",
             "Haber",
             new { controller = "Haber", action = "Listele" }
       );

       routes.MapRoute(
            "HaberDetay",
            "Haber/{id}",
            new { controller = "Haber", action = "Detay" }
        );

       routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = "" } // Parameter defaults
        );
}

如果我们按如下方式进行路由:

routes.MapRoute(
      "HaberDetay",
      "Haber/{*Id}",
      new { controller = "Haber", action = "Detay" }
);

所以如果我们在参数名旁边写*,不管News/url标签后面说什么,都会发送到Controller中Detail方法的相关参数。

例如:

http://www.doguhanaydeniz.com/Haber/Turkiye/Guncel/34389

如果请求 URL 作为土耳其 / 当前 / 34389 将作为参数发送。

【讨论】:

  • 以上答案是正确的。如果您有更多参数,例如- @Html.ActionLink("Details", "Details", "mycontroller", new { id = item.id, item2=2 item3 = "3" },null) 那么这将变成localhost:11111/files/Details/3?item2=2&item3=3,它添加了查询参数.除非你有改变的理由,否则我会使用默认的 MVC 模板。如果您将动作从 int 更改? id说int? userId 你会得到你正在寻找的查询字符串
【解决方案2】:

为什么要在链接中看到参数的名称?

Asp.Net MVC 使用用户友好的 URL。

如果您使用 MVC 模板在 Visual Studio 中创建了一个项目,那么您的路由可能默认配置为解释 controller/action/ 之后的参数,如 id。

因此,您的操作中的 id 参数值将通过模型绑定自动替换为 URL 中存在的 id 号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多