【问题标题】:Is it possible to programatically determine an ASP.NET MVC's Razor View's Model?是否可以以编程方式确定 ASP.NET MVC Razor 视图模型?
【发布时间】:2012-07-11 06:43:25
【问题描述】:

我正在手动创建一个 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

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

这可能吗?

【问题讨论】:

    标签: c# .net asp.net-mvc razor


    【解决方案1】:

    您可以通过以下代码获取 View 的类型:

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

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

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

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

    希望对您有所帮助。

    问候。

    【讨论】:

      【解决方案2】:

      该方法的泛化可以解决问题吗?

      诸如……之类的东西

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-20
        • 2011-07-06
        • 1970-01-01
        • 1970-01-01
        • 2011-05-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多