0

ここにいくつかの情報が必要です。私は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ロジックを使用して部分ビューを表示しようとしています。
4

1 に答える 1

1

ここで変更するいくつかのこと

まず、ここで:

Response.Redirect( "url to PageMain");      

代わりに

RedirectToAction( "PageMain") 

2番目-HttpGet属性を使用して、Pagemainをgetリクエストに対してのみ有効にします。

[HttpGet]
public actionResult PageMain()
{{     
   View();を返します。
//これは私が作業しているメインページです
}

3番目-このHttpPostを作成します

[HttpPost]
Public ActionResult FormAction(string tablename、FormCollection formvalues)

4番目-通常、GETメソッドとPOSTメソッドの名前は同じで、1つはHttpGetとマークされ、もう1つはもちろん異なるパラメータータイプを受け入れるHttpPostがあります。

5番目-私がお勧めするのは、ビューがDataTableに基づいていない、独自のクラスである、強く型付けされたビューであるということです-ビューの上部に「Customer」という名前を付けると、(顧客のリストの場合)のようなものが表示されたときに強く型付けされていることがわかります。 )。

@model IEnumerable <Customer>

これを行うと、FormActionメソッドはCustomerタイプのオブジェクトを自動的に取得できます。MVCのModel Binderは、フォームの値をこのオブジェクトの名前と自動的に照合し、プロパティ値を設定します。これはMVCの優れた機能の1つです。したがって、メソッドは次のようになります。

Public ActionResult FormAction(顧客顧客) 

これで、処理する顧客オブジェクトができました。

于 2011-06-05T04:31:18.647 に答える