【问题标题】:How to pass 'string' value from View to Controller by GET如何通过 GET 将“字符串”值从视图传递到控制器
【发布时间】:2016-05-16 03:06:52
【问题描述】:

我需要使用 HttpGet 将“字符串”值从 View 传递到 Controller !!

我执行以下操作,但它传递 null:

View.cshtml

@Html.ActionLink("Profile", "Index", "UserInfo", new { name = User.Identity.Name }, new { hidefocus = "hidefocus" })

UserInfoController.cs

        [HttpGet]
        public ActionResult Index(string user)
        {
            ...
        }
  • User.Identity.Name 是我的字符串。

【问题讨论】:

    标签: c# asp.net-mvc razor


    【解决方案1】:

    你可以修复它,例如:

    @Html.ActionLink("Profile", "Index", "UserInfo", new { name = User.Identity.Name }, null)
    

    【讨论】:

    • 谢谢。什么参数被清空了?
    • 空值是“object htmlAttributes”,它不是参数。见:screencast.com/t/93xgOe894b5
    • 我也可以去掉地址栏中的 ?name 吗?我希望它像 mysite.com/UserInfo/testuser 而不是 mysite.com/UserInfo?name=testuser/
    • 所以你可以使用 mvc 5 的属性:"[Route("UserInfo")]" 作为你的 ActionResult。如:screencast.com/t/xMduoP95Jo
    • 非常感谢!
    【解决方案2】:

    哦,刚刚想通了,我忘了设置参数的类型。另外,为它们设置一个名称,以防万一。

    UserInfoController.cs

            [HttpGet]
            public ActionResult Index(string name) //check for area=""
            {
             ...
            }
    

    View.cshtml

    @Html.ActionLink("Profile", "Index", "UserInfo", new { name = (string)User.Identity.Name }, new { hidefocus = "hidefocus" })
    

    现在它可以正常工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-23
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      • 1970-01-01
      相关资源
      最近更新 更多