redirectToAction导致null模型

Mas*_*low 5 asp.net-mvc

我在控制器上有2个动作:

public class CalculatorsController : Controller
{
    //
    // GET: /Calculators/

    public ActionResult Index()
    {
        return RedirectToAction("Accounting");
    }


    public ActionResult Accounting()
    {
        var combatants = Models.Persistence.InMemoryCombatantPersistence.GetCombatants();
        Debug.Assert(combatants != null);
        var bvm = new BalanceViewModel(combatants);
        Debug.Assert(bvm!=null);
        Debug.Assert(bvm.Combatants != null);
        return View(bvm);
    }

}
Run Code Online (Sandbox Code Playgroud)

调用Index方法时,我会得到一个null模型.当通过它的url直接调用Accounting方法时,我会得到一个水合模型.

Bra*_*ord 1

这与其说是一个答案,不如说是一个解决方法。我不知道为什么你会得到一个空模型,因为它看起来应该可以工作。事实上,当我亲自尝试时,我可以确认您所看到的行为。[编辑:我在最初的测试代码中发现了一个缺陷,导致我自己的空模型。现在这个问题已得到纠正,我的测试使用 RedirectToAction 可以正常工作。]如果有原因,我根本不知道。

现在的解决方法...我假设您正在这样做,因为默认路由将所有流量发送到http://www.domain.com/Calculators到“Index”。那么为什么不创建一条像这样的新路线:

routes.MapRoute(
  "Accounting",
  "Calculators/{action}/",
  new { controller = "Calculators", action = "Accounting" }
);
Run Code Online (Sandbox Code Playgroud)

此路由指定计算器控制器的默认操作为“会计”而不是索引。