带孩子的MVC PRG模式

Dis*_*ile 5 c# asp.net-mvc post-redirect-get

我试图通过使用[ImportModelStateFromTempData][ExportModelStateToTempData]动作过滤器来实现PRG模式.这种模式适用于扁平模型,但是当我有一个子集合时,我无法使它工作.我的模型看起来像这样:

public class QuestionModel
{
    public string QuestionText { get; set; }

    public ICollection<ChoiceModel> Choices { get; set; }
}

public class ChoiceModel
{
    public string ChoiceText { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的控制器如下:

[HttpGet, ImportModelStateFromTempData]
public ActionResult Create()
{
    return View();
}

[HttpPost, ExportModelStateToTempData]
public ActionResult Create(QuestionModel model)
{
     if(ModelState.IsValid)
     {
        // not getting here
     }

     return RedirectToAction("Create");
}
Run Code Online (Sandbox Code Playgroud)

我的视图允许用户向选项添加新项目,并且我验证选择必须是唯一的.当我的ModelState无效时,它会将ModelState打包成TempData并重定向到HttpGet操作.

此时,我的所有子模型值都在ModelState中,但在将模型传递给视图时它不会重建它们,因此我的视图显示添加了0个子项.

有没有办法以某种方式将ModelState与模型合并,或者我可以不将此模式与子对象一起使用?

sta*_*tak 0

检查此链接 http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#prg,您需要在其中使用ModelStateTempDataTransfer模板onActionExecution