1

I have stumbled upon this situation where I set a viewbag variable inside a MVC controller, but can't read it inside the master page, the viewbag variable shows always null in the masterpage.

I suspect that this is because the masterpage is being rendered before the page controller call, but still I need to somehow communicate backwards.

4

2 回答 2

1

我 100% 同意 @Chase Florell 但直接回答你的问题,我相信你可以使用 ViewContext.Viewbag

于 2013-07-26T17:16:41.597 回答
0

如果没有进一步了解您的业务逻辑的信息,我可能会在这里偏离基础......但是......似乎在 View 中设置任何 ViewBag 数据都是Anti-Pattern

当视图被呈现为页面生命周期的一部分时,您ViewModel应该拥有它需要的一切,并且视图和母版页应该只使用数据,而不是生成数据。

我也是一个坚定的信徒,在 ViewBag 中ViewModel而不是在 ViewBag 中设置所有相关的视图(这是个人偏好,但被广泛接受)。

如果您进一步描述您的特定场景,也许我可以帮助您想出一个更好的模式来遵循。

public class LayoutViewModel
{
   public bool UseFacebookConnect { get; set; }
}
public class SomeViewModel : LayoutViewModel
{
   public string SomeData { get; set; }
}
public class SomeController : Controller
{

    public ActionResult Index()
        {

            var someViewModel = new SomeViewModel 
                {
                    SomeData = "", 
                    UseFacebookConnect = true
                };

                return View(someViewModel);
    }
于 2013-07-26T17:14:15.820 回答