5

我的设置:

  • 查看如下路线:/Pages/Details/2
  • 页面详细信息视图必须<% Html.RenderAction("CreatePageComment", "Comments"); %>呈现评论表单
  • 评论表帖子到Comments/CreatePageComment
  • /Comments/CreatePageCommentRedirectToAction成功创建评论时返回
  • 这一切都很好

我的问题:

如果出现验证错误,我应该如何返回/Pages/Detail/1并在评论表单中显示错误?

  • 如果我使用RedirectToAction,似乎验证很棘手;我什至应该使用 Post-Redirect-Get 模式来验证错误,而不是仅仅返回?
  • 如果我返回View()它,它会让我回到显示CreateComment.aspx视图(带有验证,但只是白页上的一个表单),而不是/Pages/Details/2调用RenderAction.

如果应该使用 PRG 模式,那么我想我只需要学习如何在使用 PRG 时进行验证。如果不是——对我来说,这似乎通过返回更好地处理View()——然后我不知道如何让用户返回到初始视图,显示表单错误,同时使用RenderAction.

这感觉就像你同时敲打头部和揉腹部的游戏。我也不擅长那个。我是 MVC 的新手,所以这可能是这里的问题。

4

1 回答 1

5

我相信答案是使用 TempData,例如:

在我看来(/步骤/详细信息)我有:

<!-- List comments -->
<% Html.RenderAction("List", "Comments", new { id = Model.Step.Id }); %>

<!-- Create new comment -->
<% Html.RenderAction("Create", "Comments", new { id = Model.Step.Id }); %>

在我的评论控制器中,我有我的 POST 方法:

    // POST: /Comments/Create
    [HttpPost]
    public ActionResult Create([Bind(Exclude = "Id, Timestamp, ByUserId, ForUserId")]Comment commentToCreate)
    {
        if (ModelState.IsValid)
        {
            //Insert functionality here

            return RedirectToAction("Details", "Steps", new { id = commentToCreate.StepId });

        }

    //If validation error
        else
        {

            //Store modelstate from tempdata
            TempData.Add("ModelState", ModelState);

            //Redirect to action (this is hardcoded for now)
            return RedirectToAction("Details", "Steps", new { id = commentToCreate.StepId });
        }
    }

评论控制器中还有我的 GET 方法:

    //
    // GET: /Comments/Create

    public ActionResult Create(int id)
    {

        if (TempData.ContainsKey("ModelState"))
        {
            ModelStateDictionary externalModelState = (ModelStateDictionary)TempData["ModelState"];
            foreach (KeyValuePair<string, ModelState> valuePair in externalModelState)
            {
                ModelState.Add(valuePair.Key, valuePair.Value);
            }
        }
        return View(new Comment { StepId = id });
    }

这对我很有用,但我会很感激关于这是否是一个好的做法等的反馈。

另外,我注意到 MvcContrib 有一个 ModelStateToTempData 装饰,看起来可以做到这一点,但方式更简洁。我接下来要试试。

于 2010-01-12T16:27:47.480 回答