3

I'm manually creating a RazorView instance and manually rendering that view to my response output.

var errorController = new FakeErrorController();
var controllerContext =
    new ControllerContext(httpApplication.Context.Request.RequestContext,
                          errorController);
var view = new RazorView(controllerContext, viewPath, null, false, null);
var viewModel = new ErrorViewModel
                {
                    Exception = currentError
                };
var tempData = new TempDataDictionary();
var viewContext = new ViewContext(controllerContext, view,
                                    new ViewDataDictionary(viewModel), tempData,
                                    httpApplication.Response.Output);
view.Render(viewContext, httpApplication.Response.Output);

Works fine.

But notice how I've hard-coded the ViewModel? I was wondering if it's possible to see if the RazorView has a strongly-typed ViewModel defined.

eg. @model SomeNamespace.Model.Foo

and then create a new type, based on that. Lets also assume that there is a parameterless, default constructor.

Is this possible?

2 Answers 2

1

You can get the type of a View with the following code:

((ViewResult)otherController.Index()).Model.GetType()

The point here is that we have to cast the ActionResult as a ViewResult. It will be not enough, though, if you have actions that return other types that inherit from ActionResult (like HttpResult and so on).

Having the type, you can use reflection to instatiate it.

However, we are able to get the type only after the method call, which I believe that's not your case.

Hopefully, it'll be of some help.

Regards.

Sign up to request clarification or add additional context in comments.

Comments

1

Would generalization of the method do the trick?

Something such as...

public void MyMethod<T>(...)
    where T : class, new()
{
   // Your code
   var model = Activator.CreateInstance<T>();
   // More code
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.