3

我正在手动创建一个RazorView实例并手动将该视图呈现给我的响应输出。

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);

工作正常。

但请注意我是如何硬编码的ViewModel?我想知道是否可以查看是否定义RazorView了强类型ViewModel

例如。 @model SomeNamespace.Model.Foo

然后在此基础上创建一个新类型。我们还假设有一个无参数的默认构造函数。

这可能吗?

4

2 回答 2

1

您可以使用以下代码获取 View 的类型:

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

这里的重点是我们必须将 ActionResult 转换为 ViewResult。但是,如果您的操作返回从 ActionResult 继承的其他类型(如 HttpResult 等),这还不够。

有了类型,您可以使用反射来实例化它。

但是,我们只能在方法调用之后获取类型,我相信这不是你的情况。

希望它会有所帮助。

问候。

于 2012-07-11T23:27:49.193 回答
1

该方法的概括会起作用吗?

诸如...之类的东西

public void MyMethod<T>(...)
    where T : class, new()
{
   // Your code
   var model = Activator.CreateInstance<T>();
   // More code
}
于 2012-12-10T11:43:21.050 回答