4

メモ帳でモックアップした次のコードがあるとします。小さなエラーは許してください:)

//Default page
public ActionResult Index()
    {
        var musicViewModel
        {
         Albums = GetTopSellingAlbums(5),
         Genres = GetTopGenres(5),
         Artists = GetTopArtists(5)
         };

        return View(musicViewModel);
    }

[HttpPost]
public ActionResult Index(MusicViewModel musicViewModel)
    {

        //For the example, pretend I have a class called musicStoreSubmission in my
        //viewmodel which holds a few different fields the user fills out.

        if(ModelState.IsValid)
        {
            //Do some actions based on the user submitting a form
        }

        //Else, refresh page with errors in Modelstate.
        var musicViewModel
        {
         Albums = GetTopSellingAlbums(5),
         Genres = GetTopGenres(5),
         Artists = GetTopArtists(5)
         };

        return View(musicViewModel);
    }

私の懸念は、ModelState が無効なエラーをポストバックするには、ビューモデルを再度生成して、それらのオブジェクトを使用するページ上の要素 (ジャンル、アーティストなど) を作成できるようにする必要があることです。問題は、コードの一部を ActionResult から ActionResult にコピーして貼り付ける必要があるため、コードがあまり DRY ではないように見えることです。

このようなコードの繰り返しを避けるより良い方法はありますか? 現時点では、viewmodel が必要とするデフォルト オブジェクトの生成を別のメソッドやコンストラクターに移動しただけですが、コントローラー全体に必要なすべてのオブジェクトを生成する必要があるため、少し面倒です。私ができることを望んでいたのは、2 番目のインデックス アクションを最初のインデックス アクションにポイントし、それを通常の方法として使用することでした。私はこれを行ういくつかの異なる方法を試しましたが、ActionResult を別の ActionResult に返すことはできません。

何かご意見は?

4

2 に答える 2

6

Post/Redirect/Getパターンを適用することをお勧めします。MVC Web アプリに最適です。

コード サンプルについては、この回答を確認してください: ModelState.IsValid または Model.IsValid?

于 2011-02-18T23:01:50.027 に答える
4

次のような別のActionResultメソッドを返すことができます。

[HttpPost]
public ActionResult Index(MusicViewModel musicViewModel)
{
    if(ModelState.IsValid)
    {
        //Do some actions based on the user submitting a form
    }
    return MyAction();
}

または、投稿されたモデルをViewResultに戻すこともできます

[HttpPost]
public ActionResult Index(MusicViewModel musicViewModel)
{
    if(ModelState.IsValid)
    {
        //Do some actions based on the user submitting a form
    }
    return View(musicViewModel);
}

ViewModelを再構築しないため、2番目のアプローチの方が適しています

于 2011-02-18T22:48:07.477 に答える