0

次のようなベースコントローラーがあります

 public abstract class BaseController
    {

        protected ActionResult LogOn(LogOnViewModel viewModel)
        {
            SaveTestCookie();

            var returnUrl = "";
            if (HttpContext != null && HttpContext.Request != null && HttpContext.Request.UrlReferrer != null)
            {
                returnUrl = HttpContext.Request.UrlReferrer.LocalPath;
            }

            TempData["LogOnViewModel"] = viewModel;


            return RedirectToAction("ProceedLogOn", new { returnUrl });
        }

        public ActionResult ProceedLogOn(string returnUrl)
        {
            if (CookiesEnabled() == false)
            {
                return RedirectToAction("logon", "Account", new { area = "", returnUrl, actionType, cookiesEnabled = false });
            }
            var viewModel = TempData["LogOnViewModel"] as LogOnViewModel;

            if (viewModel == null)
            {
                throw new NullReferenceException("LogOnViewModel is not found in tempdata");
            }

            //Do something
            //the problem is I missed the values which are set in the ViewBag
        }
    }

と別のコントローラー

public class MyController : BaseController
    {

        [HttpPost]
        public ActionResult LogOn(LogOnViewModel viewModel)
        {
            // base.LogOn is used in differnet controller so I saved some details in view bag 

            ViewBag.Action = "LogonFromToolbar";
            ViewBag.ExtraData = "extra data related only for this action";

            return base.LogOn(viewModel);
        }

    }

問題は、ProceedLogOn アクション メソッドでビュー バッグの値を見逃したことです。BaseController の Logon メソッドに値があります。

ViewBag の値をあるアクションから別のアクションにコピーするにはどうすればよいですか?

だから一概には言えない this.ViewBag=ViewBag;

ViewBag にはセッターがないためです。ビューバッグを反復処理することを考えていました。試しViewBag.GetType().GetFields()てみViewBag.GetType().GetProperties()ましたが、何も返されません。

4

2 に答える 2

5

ViewData は ViewBag を反映し
ます。次のように保存した値を反復できます。

ViewBag.Message = "Welcome to ASP.NET MVC!";
ViewBag.Answer = 42;

foreach (KeyValuePair<string, object> item in ViewData)
{
    // if (item.Key = "Answer") ...
}

このリンクも役立つはずです

于 2012-07-30T09:28:19.050 に答える
-1

ViewBag をコピーする方法がわかりません。

ただし、ViewBag をそのように使用することはありません。

ViewBag は、誰かが何らかの理由で ViewModel を使用したくない場合に、出力をレンダリングするために Controller が View に与えるデータです。View は Controller について何も知らないはずですが、ViewBag は ActionName を保持しています;)。

とにかく、ProceedLogOn アクション メソッドにはかなり多くのパラメーターがありますが、実際には適切なコードではないため、現在 MyController.Logon ViewBag に保持されているパラメーターを追加することをためらう必要はありません。次に、メソッド ProceedLogOn 内に、必要なものがあります。

;)

于 2012-07-30T10:40:00.313 に答える