2011年11月5日 星期六

MVC 使用 Repository

1. 建立 MVC 專案

2. 可以看到 MVC 架構的資料夾都被建立起來了

3. 在 Models 資料夾建立新項目,選擇 「LINQ to SQL 類別」

4. 將資料表拉到畫面上

5. 在 Models 下建立一個 Interface,取名「IT0001Repository.cs」


    public interface IT0001Repository
    {
        List ListAll();
    }

6. 在 Models 下建立一個 Class,取名「T0001Repository.cs」,去實作 IT0001Repository


public class T0001Repository :IT0001Repository
    {
         private UUUDataContext _dataContext;

         public T0001Repository()
         {
             _dataContext = new UUUDataContext();
        }

         public List ListAll()
         {
            return _dataContext.T0001.ToList();
        }
    }

7.  在 Controls 下建立一個 Control ,取名「T0001Controller.cs」


 public class T0001Controller : Controller
    {
        //
        // GET: /T0001/
        IT0001Repository _repository ;

        public T0001Controller() : this(new T0001Repository()) { }

        public T0001Controller(T0001Repository repository)
        {
            _repository = repository;
        }

        public ActionResult Index()
        {
            return View(_repository.ListAll());
        }

    }

8. 以上大概都建置好了,現在要做最後一步,在 Views 下建立一個資料夾,取名「T0001」

9. 然後在 T0001 上按右鍵,加入 -> 檢視
   名稱取名「Index」,建立強型別檢視依圖設定,這樣會自動產生程式碼

10. 上面那個 View 取名 「Index」的原因,主要是在 Views -> Shared -> _Layout.cshtml
      我加了一行
  • @Html.ActionLink("T0001", "Index", "T0001")

  •       
          畫面上有一個名稱叫做T0001
          他會連結到 T0001資料夾下的Index檔案








    沒有留言:

    張貼留言