将“所有者”身份传递给相关模型的创建视图

时间:2018-11-23 06:30:48

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

我有Employees的这个视图模型:

public class EmployeeViewModel
{
    public int Id { get; set; }
    // some more properties
    public List<EmployeeReservationViewModel> Reservations { get; set; }
}

...以及EmployeeReservations的那个:

public class EmployeeReservationViewModel
{
    public int Id { get; set; }
    public int EmployeeId { get; set; }
    // some more properties
    public EmployeeViewModel Employee { get; set; }
}

Employees Details视图中,我有一个用于添加新的EmployeeReservation的链接,如下所示:

<a asp-controller="EmployeeReservations" 
   asp-action="Create">Add reservation</a>

如何将EmployeeId传递到EmployeeReservations/Create-视图?

此刻,我正在控制器中Employees的Details-method中使用这样的会话变量:

HttpContext.Session.SetInt32("EmployeeId", employee.Id);

...,然后在EmployeeReservations-controller的Create POST方法中检索它:

employeeReservation.EmployeeId = HttpContext.Session.GetInt32("EmployeeId").Value;
db.Add(employeeReservation);
await db.SaveChangesAsync();

我感觉我的方法并不理想。如果会话超时怎么办?还有另一种更安全的方法吗?

1 个答案:

答案 0 :(得分:2)

您可以使用asp-route-id

可见

<a asp-controller="EmployeeReservations" 
   asp-action="Create" asp-route-id="10">Add reservation</a>

在Controller中添加id作为创建操作的参数

Public IActionResult Create(string id){
}