Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 929
Pure.Krome Avatar asked Nov 22 '25 06:11

Pure.Krome


2 Answers

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.

like image 97
Andre Calil Avatar answered Nov 24 '25 18:11

Andre Calil


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
}
like image 37
Isaac Llopis Avatar answered Nov 24 '25 20:11

Isaac Llopis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!