从代码创建强类型视图并加载它

时间:2011-05-13 20:49:29

标签: c# asp.net-mvc strongly-typed-view

我创建的强类型视图页面如下所示:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Models.Reports.OverallResultsViewModel>" %>

我正在尝试在代码中创建视图页面并在不显示的情况下呈现它:

System.Web.Mvc.ViewPage<Models.Reports.OverallResultsViewModel> page2 = new ViewPage<Models.Reports.OverallResultsViewModel>();

以下是实施的视图模型:

public class OverallResultsViewModel {
    public OverallResultsViewModel(string name, string draft, IEnumerable<Subject> subjects, IEnumerable<IResult> results) {
        this.Name = name;
        this.Draft = draft;
        this.Subjects = subjects;
        this.Results = results;
    }

    public IEnumerable<Subject> Subjects { get;  set; }
    public IEnumerable<IResult> Results { get;  set; }
    public string Name { get;  set; }
    public string Draft { get;  set; }
}

我在想我会使用以下代码将值传递给视图模型:

page2.Model.Draft = Draft;
page2.Model.Results = page2Data;
page2.Model.Subjects = subjects;
page2.Model.Name = Name;

但我得到一个错误,说Model是null。如何初始化Model以便我可以在其上设置变量?

1 个答案:

答案 0 :(得分:2)

尝试:

page2.ViewData.Model = new OverallResultsViewModel(
                   Name, Draft, subjects, page2Data
 );