ここにいくつかの情報が必要です。私は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
さて、今、私の質問は次のとおりです。そのような構造は有効ですか(ここで有効とは、それが適切に構造化されているか、より良い方法があるかどうかを意味します)?ModelState.AddModelError()
パーシャルビュー'Partial1'のメソッドで例外に到達するにはどうすればよいですか?
混乱している場合は、要約すると次のようになります。
- PageMainには、url-parameterに従って作成されたテーブルがあります。実際には、別の部分ビューで作成されていますが、PageMainに表示されます
- テーブルを編集すると、フォームはフォームアクションにリダイレクトします。フォームアクションは、データベースを編集するためにコードが実行されます。
- 最後に、エラーが発生した場合、ユーザーはFormActionに残りますが、このページで使用されるビューは引き続きPageMainです。同じページを2回作成するようなものであるため、このページに別のビューはありません。つまり、別のビューを作成したくないエラーを示す部分ビューを含めるだけです。代わりに、エラーが発生した場合にのみ、if-elseロジックを使用して部分ビューを表示しようとしています。