MVC Passing ViewBag value from another controller

安稳与你 提交于 2019-12-03 05:15:59

问题


I've set a value into Viewbag.message in my default HomeController and successfully display it in my Shared/_Layout.cshtml.

After that I added another TestController and in the TestController view, Viewbag.message seems to be null. May I know what's wrong with it.

Correct me if I'm wrong,from my understanding Viewbag.Message should be available from all over the places?


回答1:


ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.

  • It’s life also lies only during the current request. If redirection occurs then it’s value becomes null.
  • It doesn’t required typecasting for complex data type.

Below is a summary table which shows different mechanism of persistence.

Credit:CodeProjectArticle


回答2:


[HttpPost]
public ActionResult Index()
{
    TempData["Message"] = "Success";
    return RedirectToAction("Index");
}


public ActionResult Index()
{
    ViewBag.Message=TempData["Message"];
    return View();
}



回答3:


//one controller to another controller you need to use seesion 
//this is Home controller

[httpPost]
public actionresult Index()
{
    session["Message"] = "Welcome to session tutorial";
    return redirectToAction("Index","About");
}

//now pass to the another About controller

[httpPost]
public actionresult About()
{
    viewbag. message = session["Message"]
    return view();
}


来源:https://stackoverflow.com/questions/18479297/mvc-passing-viewbag-value-from-another-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!