我需要一些信息。因此,对于你们来说,我对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()
方法中达到异常?
如果你感到困惑,总结一下:
答案 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)
现在你有一个客户对象来处理。