Pure.Krome
Pure.Krome

Reputation: 86997

Is it possible to programatically determine an ASP.NET MVC's Razor View's Model?

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?

Upvotes: 3

Views: 599

Answers (2)

Isaac Llopis
Isaac Llopis

Reputation: 432

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
}

Upvotes: 1

Andre Calil
Andre Calil

Reputation: 7692

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.

Upvotes: 1

Related Questions