【问题标题】:how to pass multiple parameter to controller via actionlink and output in the view?如何通过actionlink将多个参数传递给控制器​​并在视图中输出?
【发布时间】:2012-09-01 15:30:11
【问题描述】:

我对 asp.net mvc3 还很陌生,我很难弄清楚这一点。 我有一个动作链接,我想包含一个参数并传递给我的索引方法

@Html.ActionLink("Click here", "Index", "Customer", new { customerid = item.custId}, new {       @class = "partiallink" })

我如何从控制器接收它?考虑到我的 Index Action 方法中没有方法参数,以及如何在视图中输出参数?

我想我想说的是把它传递给一些控制器方法并仍然返回带有参数的索引页面

【问题讨论】:

  • 您是否尝试将 customerid 传递给 Index?但它不包含任何参数。

标签: asp.net-mvc


【解决方案1】:

你可以使用类似于下面的例子

@Html.ActionLink("Click here", "Index", "Customer", new { ID= 111,UID =222}, null)

在控制器中

[HttpGet,Route("Index/{ID}/{UID}")]
        public ActionResult EventView(int ID,int UID)
        {
        }

请参考下面的链接,很有用

Query string not working while using attribute routing

【讨论】:

    【解决方案2】:

    您传递给操作链接的所有参数都成为查询字符串参数,即

    @Html.ActionLink("Click here", "Index", "Customer", new { customerid = 111, someOtherParameter = 222, anotherParameter = 333}
    

    转移到链接/Customer/Index?customerid=111&someOtherParameter=222&anotherParameter=333。 您可以通过Request.QueryStringproperty 在控制器中获取它,或者如果 Index 操作的签名为:

    ActionResult Index(int? customerid, int? someOtherParameter, string anotherParameter)
    {
        .....
    }
    

    【讨论】:

      【解决方案3】:

      您是说,在您的客户控制器上,您希望能够将任何值或 customerid 传递给返回索引页面的索引操作吗?

      假设您没有更改默认路由,您可以更改控制器操作以接受可为空的 int,然后根据 customerid 是否为空来获取您的模型:

          public ActionResult Index(int? customerid)
          {
              YourModelType model;
              if (customerid == null)
              {
                  model = /* however you get your model when you don't have an id */
              }
              else
              {
                  model = /* however you get your model when you have an id */;
              }
      
              return View("Index", model);
          }
      

      您还需要更新您的路由引擎以接受可选的 customerid 参数:

              routes.MapRoute(
                  "Customer", // Route name
                  "Customer/{action}/{customerid}", // URL with parameters
                  new { controller = "Customer", action = "Index", customerid = UrlParameter.Optional } // Parameter defaults
              );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-28
        • 1970-01-01
        • 1970-01-01
        • 2017-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多