使用参数重定向到另一个操作时,属性变为 NULL

Kok*_*efa 2 c# asp.net-mvc

我正在 C# 中的 MVC asp.net 编程项目中工作。

我的arena班级有 5 个属性:

 public int Id { get; set; }
 public int CharacterId { get; set; }
 public int Forfeit { get; set; }
 public System.DateTime Queued { get; set; }   
 public virtual Character Character { get; set; }
Run Code Online (Sandbox Code Playgroud)

当我Arena使用这个从数据库中获取模型时:

 var arenaModel = ctx.Arenas.FirstOrDefault(a => a.Character.AccountId == currentUserId);
Run Code Online (Sandbox Code Playgroud)

没有什么是空的,有一个字符,有 id,没收并排队。但是当我使用这个重定向到另一个动作时:

 return RedirectToAction("BattleNPC", arenaModel);
Run Code Online (Sandbox Code Playgroud)

并在 BattleNPC 方法中使用断点

 public ActionResult BattleNPC(Arena model)
 {
     var character = model.Character; // <-- Null
 }
Run Code Online (Sandbox Code Playgroud)

突然属性为Character空,我仍然可以看到其他属性正常但Character变为空。

这是为什么?有人可以解释为什么Character变成空值。我知道如何修复它,我只是不明白为什么它会变为空。

flo*_*ler 5

RedirectToAction通知:您的浏览器重定向到一个新的URL。模型在此过程中丢失了,因为浏览器只会执行新的 GET 请求。您可以以键值形式添加参数。这将被添加到 URL

RedirectToAction('actionX', new { id = 123 })
Run Code Online (Sandbox Code Playgroud)

然后,您的 Action 将根据给定的 id 获取 DataObject。

public ActionResult BattleNPC(int arenaId)
{
  var model = var arenaModel = ctx.Arenas.FirstOrDefault(a => a.Id == arenaId);
  var character = model.Character; // <-- Null
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您的操作位于同一个控制器中,只需使用 view() 返回

请参阅:您何时使用 View() 与 RedirectToAction 或:redirectToAction() 和 View() 之间的区别