【发布时间】:2021-02-20 05:02:02
【问题描述】:
我正在尝试执行POST,其中模型具有外键字段,但我想将此值设置为创建者的 ID。我有一个名为“Store”的模型,带有 ApplicationUserId FK 。我尝试将包含ApplicationUserId 的新对象“Store”传递给GET 视图,但是当我提交时,ApplicationUserId 字段为空。我也尝试在控制器上手动设置字段,但此时模型状态已经无效
我的行动:
public async Task<IActionResult> Create(Store store)
{
store.ApplicationUser = currentUser
if (ModelState.IsValid)
{
_context.Add(store);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(store);
}
我的模特:
public class Store
{
public int Id { get; set; }
public string Name { get; set; }
[Required]
[ForeignKey("ApplicationUserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
}
【问题讨论】:
-
您的操作 Create(Store store) 是为了什么?您是要在屏幕上显示视图还是在数据库中保存存储。在您被某人否决之前,请向我们展示更多代码。
-
如果值到达 null,那几乎总是一个序列化问题。你的模型商店怎么样,你可以用它来编辑你的帖子吗?以及如何获得“当前用户”?
-
@Sergey,这是为了保存在数据库中,我编辑了帖子。
-
@RodRamírez,我使用“UserManager”类获取当前用户。只有 ApplicationUserId 为空。我用我的模型编辑了帖子。
-
抱歉,我在您的 Store 类中没有看到 UserId 属性
标签: c# asp.net-mvc asp.net-core .net-core