【问题标题】:Sending multiple parameters to Actions in ASP.NET MVC向 ASP.NET MVC 中的操作发送多个参数
【发布时间】:2011-01-03 16:44:42
【问题描述】:

我想向 ASP.NET MVC 中的操作发送多个参数。我还希望 URL 看起来像这样:

http://example.com/products/item/2

代替:

http://example.com/products/item.aspx?id=2

我也想对发件人做同样的事情,这是当前的 URL:

http://example.com/products/item.aspx?id=2&sender=1

如何在 ASP.NET MVC 中使用 C# 完成这两者?

【问题讨论】:

    标签: c# .net asp.net-mvc


    【解决方案1】:

    如果您可以在查询字符串中传递内容,这很容易。只需更改 Action 方法以获取具有匹配名称的附加参数:

    // Products/Item.aspx?id=2 or Products/Item/2
    public ActionResult Item(int id) { }
    

    会变成:

    // Products/Item.aspx?id=2&sender=1 or Products/Item/2?sender=1
    public ActionResult Item(int id, int sender) { }
    

    ASP.NET MVC 将为您完成所有工作。

    如果您想要一个干净的 URL,您只需将新路由添加到 Global.asax.cs:

    // will allow for Products/Item/2/1
    routes.MapRoute(
            "ItemDetailsWithSender",
            "Products/Item/{id}/{sender}",
            new { controller = "Products", action = "Item" }
    );
    

    【讨论】:

    • 不要忘记在 global.asax 中为路线设置适当的定义。
    • @Reza - 我已在代码中将 URL 添加为 cmets。如果您想要更简洁的 URL,则需要向 global.asax.cs 添加自定义路由。
    【解决方案2】:

    如果您想要一个漂亮的网址,请将以下内容添加到您的global.asax.cs

    routes.MapRoute("ProductIDs",
        "Products/item/{id}",
        new { controller = Products, action = showItem, id="" }
        new { id = @"\d+" }
     );
    
    routes.MapRoute("ProductIDWithSender",
       "Products/item/{sender}/{id}/",
        new { controller = Products, action = showItem, id="" sender="" } 
        new { id = @"\d+", sender=@"[0-9]" } //constraint
    );
    

    然后使用所需的操作:

    public ActionResult showItem(int id)
    {
        //view stuff here.
    }
    
    public ActionResult showItem(int id, int sender)
    {
        //view stuff here
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用任何路由规则,例如:

      {controller}/{action}/{param1}/{param2}
      

      你也可以使用像:baseUrl?param1=1&param2=2这样的get params

      并查看this link,希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2014-04-10
        • 1970-01-01
        • 2017-08-25
        • 1970-01-01
        • 2010-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多