【发布时间】:2013-03-01 08:13:22
【问题描述】:
我需要一些信息。我是 MVC 的新手,因此对你们来说,我认为这将是一个容易回答的问题。我有以下结构:
Controller.cs
Public ActionResult PageMain() {
return View(); // this is the main page I'm working with
}
[ChildActionOnly]
Public PartialViewResult Partial1(string tablename) {
//Some code to construct datatable according to the url parameter
return PartialView("Partial1", DataTable);
}
Public ActionResult FormAction(string tablename, FormCollection formvalues) {
//Here I send the values to the model in which I have a public void
//that updates the database -> I'm not using Linq at this phase because
//both the tables and fields are dynamic
//I execute the code in a try and catch statement
try
{
//some code
Response.Redirect("url to PageMain");
}
catch (Exception ex) {
ModelState.AddModelError("Error", ex);
Return View("PageMain", ex);
// actually, here I'd like to send the exception error
// to the partialview which renders the error as its model but
// but I don't know how since if I use return PartialView()
// then only the partial view will be displayed, not the whole page
}
}
最后,在 PageMain 视图中我有:
//Some initial code with the form that posts value to FormAction
@Html.RenderPartial("Partial1") //this is the partial which shows error
//it is only displayed when the form is posted
//and there is an error
好的,现在,我的问题是:这样的结构是否有效(这里所说的有效是指结构是否良好或有更好的方法)?以及如何在 Partial View 'Partial1' 的 ModelState.AddModelError() 方法中达到异常?
如果您感到困惑,总结一下:
- 在PageMain中,有一个按照url-parameter构造的表。实际上, 它是在另一个部分视图中构造的,但显示在 PageMain 中
- 当我编辑表格时,表单将我重定向到 FormAction,执行代码 编辑数据库
- 最后,如果有错误,用户仍然在FormAction中,但是在这个页面中,使用的视图仍然是PageMain,我没有为这个页面设置不同的视图,因为它就像两次构建同一个页面一样。我的意思是,只包含一个显示我不想创建另一个视图的错误的局部视图。相反,我试图仅在出现某些错误的情况下使用一些 if - else 逻辑使部分视图可见
【问题讨论】:
标签: asp.net-mvc structure partial-views modelstate