ViewDataFactory and strongly typed master pages

こ雲淡風輕ζ 提交于 2019-12-05 04:31:51

问题


Im trying to get my strongly typed master page to work in my ASP MVC 2.0 application. I have come far with the help of these two posts:

Passing data to Master Page in ASP.NET MVC

Strongly Typed ASP.Net MVC Master Pages

Problem is that im not sure how to get that ViewDataFactory code to work, this is my code:

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

When I build the solution I get the follwing build error:

"; expected" in ViewDataFactory.cs

Which points to the code snippet:

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

I guess im missing something essential, im new to this and any help would be appreciated!


回答1:


Why don't you just add a semicolon at the end of that line? :)

Abstract methods (as well as interface methods) have a semicolon in place of a body.




回答2:


I finally got it working thanks to Aviad P.'s suggestions and some trial and error.

This is how my IViewDataFactory ended up looking like:

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


来源:https://stackoverflow.com/questions/1989927/viewdatafactory-and-strongly-typed-master-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!