会话/临时数据与asp.net核心相关数据的策略

时间:2016-09-01 20:14:18

标签: asp.net-core asp.net-core-mvc

我有一个包含公司列表的入口页面。

公司视图有一个打开按钮,使用附加的companyId重定向到Departments索引视图,因为需要显示该公司的Departments:

 public IActionResult OpenCompany(int id)
 {
return RedirectToRoute(new { Controller = "Departments", Action = "Index", CompanyId = id });
 }

现在显示包含所有现有部门的我的部门索引视图。

在该表上是"Create Department"按钮。但我不能创建那个部门,因为我需要那个CompanyId。

如何获得该CompanyId?

1 个答案:

答案 0 :(得分:1)

您可以将此信息(公司ID)传递给索引操作,并根据需要使用它。

将新属性添加到部门索引操作的视图模型

public class DepartmentIndexVm
{
  public int? CompanyIdCameFrom { set;get;}
  // Add Other properties for the index action as needed
}

现在在部门索引操作中,

public ActionResult Index(int? id)
{
  var vm = new DepartmentIndexVm { CompanyIdCameFrom = id }); 
  return View(vm);
}

现在在部门索引视图中,只需在创建“创建部门”链接/按钮时使用此CompanyIdCameFrom属性值

@model DepartmentIndexVm
<a asp-action="create" asp-controller="department"
                                  asp-route-companyId="@Model.CompanyIdCameFrom">Create</a>

假设您的create操作方法接受companyId参数

public ActionResult Create(int? companyId)
{
  // to do  : return something
}

如果您不喜欢视图模型方法,可以考虑使用ViewBag。而不是设置为视图模型属性,设置为ViewBag并在构建链接时使用它。

相关问题