Rog*_*ers 5 asp.net-mvc post-redirect-get renderaction
我的设置:
/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的新手,所以这可能是问题所在.
我相信答案是使用TempData,例如:
在我看来(/步骤/细节)我有:
<!-- List comments -->
<% Html.RenderAction("List", "Comments", new { id = Model.Step.Id }); %>
<!-- Create new comment -->
<% Html.RenderAction("Create", "Comments", new { id = Model.Step.Id }); %>
Run Code Online (Sandbox Code Playgroud)
在我的评论控制器中,我有我的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 });
}
}
Run Code Online (Sandbox Code Playgroud)
在评论控制器中也是我的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 });
}
Run Code Online (Sandbox Code Playgroud)
这对我很有用,但我很感激这是一个好习惯的反馈,等等.
另外,我注意到MvcContrib有一个ModelStateToTempData装饰,看起来这样做,但是更清洁.我接下来要尝试一下.
| 归档时间: |
|
| 查看次数: |
2093 次 |
| 最近记录: |