【问题标题】:Null route value passes in ActionLink空路由值在 ActionLink 中传递
【发布时间】:2016-01-17 22:51:58
【问题描述】:

我是 Asp.net MVC 的新手。我想以这种方式创建模型的某些对象的超链接

  <ul>@foreach(Department department in @Model ) 
    {         
      <li>@Html.ActionLink(department.Name, "Index", "Employee", new {departmentid= department.Id },null)</li>   
    } </ul>

现在如图所示,当我在浏览器中单击链接时,它应该移动到具有部门.Id 路由值的员工控制器的索引操作。但是当我单击链接时,它传递了一个空路由值,但是在 URL 中,它显示了正确的值。为什么会这样?有什么帮助吗?

这是 Employee 控制器中的索引操作

 public ActionResult Index(int id)
        {
            List<Employee> employees = new List<Employee>();

             employees.AddRange(db.Employees.ToList().Where(x => x.DepartmentId == id));

            return View(employees);
        }

【问题讨论】:

  • 你的动作是什么样的?可能是参数名称不匹配
  • 哪些参数名称?你能解释一下吗? @利亚姆
  • new {departmentid= department.Id }更改为new {id= department.Id }

标签: asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

你实施你的行动是错误的。匿名对象 (new {departmentid= department.Id }) 中的名称和参数名称必须匹配。将 departmentid 更改为 id(因为您的操作需要一个名为 id Index(int id) 的参数):

@Html.ActionLink(department.Name, "Index", "Employee", new {id= department.Id },null)

【讨论】:

  • 哦……我以为这只是一个别名……非常感谢。它有效:)
  • 它使用reflection 来匹配它们,因此名称必须匹配