Asp.net mvc c#mvc结构-简单问题
我需要一些信息。我是MVC的新手,所以对你们来说,我想这将是一个很容易回答的问题。我的结构如下: 控制器Asp.net mvc c#mvc结构-简单问题,asp.net-mvc,structure,partial-views,modelstate,Asp.net Mvc,Structure,Partial Views,Modelstate,我需要一些信息。我是MVC的新手,所以对你们来说,我想这将是一个很容易回答的问题。我的结构如下: 控制器 Public ActionResult PageMain() { return View(); // this is the main page I'm working with } [ChildActionOnly] Public PartialViewResult Partial1(string tablename) { //Some code to constr
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
好的,现在,我的问题是:这样的结构有效吗(这里我所说的有效是指结构良好还是有更好的方法)?如何在部分视图“Partial1”中的ModelState.addmodeleror()方法中访问异常
如果您感到困惑,总结一下:
- 在PageMain中,有一个根据url参数构造的表。事实上
它在另一个partialview中构造,但显示在PageMain中
- 当我编辑表格时,表单将我重定向到FormAction,代码将在其中执行
编辑数据库
- 最后,如果有错误,用户仍然在表单中,但在这个页面中使用的视图仍然是PageMain,我没有为这个页面创建不同的视图,因为这就像构建同一个页面两次一样。我的意思是,只包含一个partialview,它显示了我不想创建另一个视图的错误。取而代之的是,我试图仅在出现一些错误的情况下,使用一些if-else逻辑使局部视图可见
这里有几件事我想改变
首先,这里:
Response.Redirect("url to PageMain");
重定向(“指向PageMain的url”);
您想返回一个
RedirectToAction("PageMain")
重定向到操作(“PageMain”)
第二个-使用HttpGet属性使Pagemain仅对get请求有效
[HttpGet]
public actionResult PageMain()
{
return View();
// this is the main page I'm working with
}
[HttpGet]
公共行动结果页面main()
{
返回视图();
//这是我正在使用的主页
}
第三,制作这个HttpPost
[HttpPost]
Public ActionResult FormAction(string tablename, FormCollection formvalues)
[HttpPost]
Public ActionResult FormAction(字符串表名、FormCollection formvalues)
第四-
通常您会看到,GET方法和POST方法的名称相同,其中一个标记为HttpGet,另一个HttpPost接受不同的参数类型
第五-
我建议您的视图是一个强类型视图,它不是基于DataTable,而是基于您自己的类,比如命名为“Customer”
在视图的顶部,当您看到以下内容时,您就知道它是强类型的(对于客户列表)
@模型IEnumerable
执行此操作时,FormAction方法可以自动获取Customer类型的对象—MVC中的模型绑定器会自动将表单值与此对象中的名称匹配,并设置属性值。这是MVC的重要特性之一。因此,您的方法将成为:
Public ActionResult FormAction(Customer customer)
公共行动结果形成行动(客户)
现在您需要处理一个客户对象。感谢您的回复,这很有帮助!。问题是页面返回一个datatable,因为我返回的是基于url参数的sql表。不过,还是要谢谢你的提示!
Public ActionResult FormAction(Customer customer)