0

When I access ViewData inside a method in the controller, I am able to assign the value in the form of dictionary ie.

ViewData["message"]="this is a custom message";

but I got into a scenario where I was trying to handle the Exception in MVC, here is my code:

 public void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled && (filterContext.Exception is ArgumentOutOfRangeException))
            {
                filterContext.Result = new ViewResult { ViewName = "Error", ViewData = };
                filterContext.ExceptionHandled = true;
            }
        }

Now when handling exception i would like to pass a message to the error page, so tried to access the Result property of the ExceptionContext. Now

my question is why am I not able to assign a value to the ViewData in a dictionary-like a format here

filterContext.Result = new ViewResult { ViewName = "Error", ViewData = };

This is also a property returning a ViewDataDictionary object, when am I able to assign a value in the Controller method like this ViewData["message"] = "argument exception error"; the why am I not able to do the same inside the ViewResult object.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Lijin Durairaj
  • 4,910
  • 15
  • 52
  • 85

1 Answers1

0

I tried it myself and got an understanding on the inner workings of the MVC frameWork, please correct me if I am wrong and please provide an explanation for it, which would make to learn more about the framework.

When I access ViewData inside a method in the controller, I am able to assign the value in the form of dictionary

This is because when we call the controller and the method, MVC takes responsibilty to assign objects to all the properties, thats the reason we could assign value for the ViewData inside the method.

filterContext.Result = new ViewResult { ViewName = "Error", ViewData = };

When we are dealing with the ViewData property of the ViewResult class, we cannot assign the value, in this way ViewData["key"]="some value" because it requires ViewDataDictionary object. however we can do this to assign the value like this

 var d = new ViewDataDictionary();
                d["key"] = "some value";
                filterContext.Result = new ViewResult { ViewName = "Error",ViewData=d };
Lijin Durairaj
  • 4,910
  • 15
  • 52
  • 85