ViewDataFactory和强类型母版页

时间:2010-01-01 22:46:39

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

我试图让我的强类型母版页在我的ASP MVC 2.0应用程序中工作。 我在这两个帖子的帮助下走得很远:

Passing data to Master Page in ASP.NET MVC

Strongly Typed ASP.Net MVC Master Pages

问题是我不确定如何使ViewDataFactory代码工作,这是我的代码:

BaseController.cs

public class BaseController : Controller
{        
    private IPageRepository _repPage;

    public BaseController(IPageRepository repPage)
    {
        _repPage = repPage;
    }

    protected T CreateViewData<T>() where T : MasterViewData, new()
    {
        IViewDataFactory factory = new ViewDataFactory();

        IEnumerable<Page> pages = _repPage.GetAllPages();

        return factory.Create<T>(pages);
    }
}

HomeController.cs

public class HomeController : BaseController
{
    public ActionResult Index()
    {
        HomeViewData viewData = CreateViewData<HomeViewData>();

        viewData.Name = "Test";

        return View("Index", viewData);
    }

    public ActionResult About()
    {
        return View();
    }
}

ViewDataFactory.cs

public interface IViewDataFactory
{
    T Create<T>(IEnumerable<Page> pages) where T : MasterViewData, new()
}

public class ViewDataFactory : IViewDataFactory
{
    public ViewDataFactory()
    {
    }  
}

HomeViewData.cs

public class HomeViewData : MasterViewData
{
    public string Name { get; set; }
}

MasterViewData

public class MasterViewData
{
    public IEnumerable<Page> Pages { get; set; }
}

当我构建解决方案时,我得到了以下构建错误:

"; expected" in ViewDataFactory.cs

指向代码段:

T Create<T>(IEnumerable<Page> pages) where T : MasterViewData, new()

我想我错过了一些必不可少的东西,我对此很新,任何帮助都会受到赞赏!

2 个答案:

答案 0 :(得分:6)

为什么不在该行的末尾添加分号? :)

抽象方法(以及接口方法)使用分号代替正文。

答案 1 :(得分:1)

由于Aviad P.的建议和一些反复试验,我终于明白了。

这就是我的IViewDataFactory最终看起来像:

public interface IViewDataFactory
{
    T Create<T>(IEnumerable<Page> pages) where T : MasterViewData, new();
}

public class ViewDataFactory : IViewDataFactory
{        
    public T Create<T>(IEnumerable<Page> pages) where T : MasterViewData, new()
    {
        T t = new T();
        t.Pages = pages;
        return t;
    }
}