【问题标题】:MVC 4 Html.ActionLink is not passing parameters to controllerMVC 4 Html.ActionLink 未将参数传递给控制器
【发布时间】:2016-01-23 23:51:13
【问题描述】:

我对 MVC 有点陌生,并试图将登录页面重写为 MVC。 我无法在控制器中将参数传递给我的 ActionResult,传入的参数为空。

这里是视图

 <div class="form-group">
<div class="row">
@Html.TextBoxFor(model => model.UserName)
</div>
 </div>

<button class="btn btn-primary">
@Html.ActionLink("GO!", "AppList", "LogIn", new { @userName = Model.UserName}, null)
</button>

我正在尝试将用户名和密码传递给我的控制器。

  public ActionResult AppList(string userName)
        {
            return View();
        }

我查看了其他帖子,我确定我为此使用了适当的重载。

这里我添加了路由配置

  routes.MapRoute(
                name: "LogIn",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "LogIn", action = "Index", id = UrlParameter.Optional }
            );

这是我正在加载登录页面的 actionResult

public ActionResult LogIn(string userName, string password)
        {
            ViewBag.LogInButton = "Log In";

            return View(new Login());
        }

并查看我分配的模型

@model LogInPortal.Controllers.LogInController.Login

【问题讨论】:

  • Model.UserName 是非空值吗?
  • @Shyju 你是说我的模特吗?是的,它不是一个可以为空的字段 public class Login { public string UserName { get;放; } 公共字符串密码 { 获取;放; } }
  • 您的代码对我来说看起来不错。您是否更改了默认路由定义?
  • 没有。我的意思是 Model.UserName 属性的值
  • @Shyju - 是的,值为 null,我编辑了帖子以显示配置

标签: asp.net-mvc-4 actionresult


【解决方案1】:

点击链接会发出 GET 请求,但不会提交表单数据。您需要在表单中使用提交按钮来提交表单字段值

@model LogInPortal.Controllers.LogInController.Login
@using(Html.BeginForm("Login","AppList"))
{
  <div class="row">
    @Html.TextBoxFor(model => model.UserName)
  </div>
  <div class="row">
    @Html.TextBoxFor(model => model.Password)
  </div>
  <input type="submit" />
}

并使用 HttpPost 属性标记您的操作方法

[HttpPost]
public ActionResult LogIn(string userName, string password)
{
  // do something with the posted data and return something
}

或者您甚至可以使用相同的登录类对象作为您的参数。默认模型绑定器会将发布的表单数据映射到该对象的属性值。

[HttpPost]
public ActionResult LogIn(Login model)
{
  // do something with model.UserName and model.Password
  // to do : return something
}

【讨论】:

  • 我在上面尝试过在我设法传递参数后仍然在我的控制器中获得空参数,我将更新它以发布,试图在这里获取骨骼:)
  • 您确定您的 GET 操作请求在查询字符串中有用户名和密码吗?
  • 现在刚刚检查了提琴手,没有查询字符串进来:/
  • 我猜你需要解决这个问题。我认为您需要了解如何将数据从您的操作方法传递到视图。看看this
  • 感谢您的链接,在我的情况下,我试图将数据从文本框传递到我的 actionResult。如果我将日期从 ActionResult 传递到视图,它工作正常 :)
猜你喜欢
  • 2012-12-18
  • 2011-02-18
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
相关资源
最近更新 更多