c#mvc结构 - 简单的问题

时间:2011-06-04 14:31:31

标签: asp.net-mvc structure partial-views modelstate

我需要一些信息。因此,对于你们来说,我对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 View中我有:

//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

好的,现在,我的问题是:这样的结构是否有效(这里有效我的意思是,如果结构良好或有更好的方法)?如何在部分视图'Partial1'中的ModelState.AddModelError()方法中达到异常?

如果你感到困惑,总结一下:

  • 在PageMain中,有一个根据url-parameter构造的表。其实, 它是在另一个部分视图中构建的,但显示在PageMain
  • 当我编辑表格时,表单会将我重定向到FormAction,执行代码 编辑数据库
  • 最后,如果有错误,用户仍然在FormAction中,但在此页面中使用的View仍然是PageMain,我对此页面没有不同的视图,因为它就像构建同一页面两次。我的意思是,只包括一个部分视图,显示我不想创建另一个视图的错误。相反,我试图使用一些if - else逻辑使部分视图可见,只有在出现一些错误时

1 个答案:

答案 0 :(得分:1)

我会在这里改变一些事情

首先,在这里:

 Response.Redirect("url to PageMain");      

您希望改为返回

RedirectToAction("PageMain") 

秒 - 使用HttpGet属性使Pagemain仅对get请求有效。

[HttpGet]
public actionResult PageMain() 
{     
   return View(); 
// this is the main page I'm working with
}

第三 - 制作这个HttpPost

[HttpPost]
Public ActionResult FormAction(string tablename, FormCollection formvalues) 
第四 - 通常你会看到人们有GET方法和POST方法有相同的名字,一个标记为HttpGet,一个HttpPost接受当然不同的参数类型。

第五 - 我建议您的视图是一个强类型视图,不是基于DataTable而是基于您自己的类 - 比如名为“Customer” 在您的视图顶部,当您看到(对于客户列表)

之类的内容时,您会知道它的强类型
@model IEnumerable<Customer>

执行此操作时,FormAction方法可以自动获取Customer类型的对象 - MVC中的Model Binder会自动将您的表单值与此对象中的名称匹配,并设置属性值。这是MVC的一大特色。所以你的方法将成为:

Public ActionResult FormAction(Customer customer) 

现在你有一个客户对象来处理。