3

I've writen a very simple Actionresult which derives from ViewResult

    public class FormResult : ViewResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            context.Controller.ViewBag.Form = "value";

            base.ExecuteResult(context);
        }
    }

It basically just adds a value to ViewBag.

Then I'm returning it in the action method.

    public ActionResult Index()
    { 
        return new FormResult();
    }

The problem is, the ViewBag is empty in the appropriate view.

Am I missing something here ?

user49126
  • 1,825
  • 7
  • 30
  • 53

1 Answers1

4

You have to pass ViewData from the controller.

public ActionResult Index()
{ 
    return new FormResult
    {
        ViewData = ViewData
   };
}

If you see the source code of the View() method this what it is

protected internal virtual ViewResult View(string viewName, string masterName, object model)
{
    if (model != null)
    {
        ViewData.Model = model;
    }

    return new ViewResult
    {
        ViewName = viewName,
        MasterName = masterName,
        ViewData = ViewData,
        TempData = TempData,
        ViewEngineCollection = ViewEngineCollection
    };
}

The ViewData, TempData,.. are passed from the controller.

VJAI
  • 32,167
  • 23
  • 102
  • 164