ASP.NET Core開發-MVC 使用dotnet 命令建立Controller和View

使用dotnet 命令在ASP.NET Core MVC 中建立Controller和View,以前講解過使用yo 來建立Controller和View。web

下面來了解dotnet 命令來建立Controller和View,功能更增強大,更加完整。api

結合VS Code 使你能跨平臺更好更快速的開發 ASP.NET Core MVC。ui

也就能夠在 Linux 和Mac 中更好的開發ASP.NET Core 應用程序。spa

 

建立ASP.NET Core應用程序

dotnet new -t web

dotnet restore

dotnet run

 

建立好之後,咱們來添加 Controller和View。rest

建立使用的dotnet命令爲: dotnet aspnet-codegeneratorcode

 

建立Controller

1.空白Controller

dotnet aspnet-codegenerator controller -name LineZero -outDir Controllers

2.增刪查改Controller

dotnet aspnet-codegenerator controller -name LineZero -actions -outDir Controllers

命令增長一個:-actions  blog

3.增刪查改+EF Controller

生成增刪查改的action 及對應的視圖。ci

dotnet aspnet-codegenerator controller -name LineZeroController -m ApplicationUser -dc ApplicationDbContext -outDir Controllers

-m 指的是model開發

-dc 指 DbContext generator

4.API Controller

dotnet aspnet-codegenerator controller -name LineZeroController -m ApplicationUser -dc ApplicationDbContext -api -outDir Controllers

增長一個 -api 就表明是生成api controller 

更多命令能夠參考幫助:dotnet aspnet-codegenerator controller -?

 

建立View

1.建立View

能夠指定什麼操做,Create|Edit|Delete|Details|List ,必須填入對應的model

dotnet aspnet-codegenerator view Index List -m ApplicationUser -f -outDir Views\LineZero

這裏咱們就建立了一個名爲:Index   操做爲:List 的View 

-f 若是存在該文件則覆蓋文件。dotnet aspnet-codegenerator 默認是不覆蓋文件。

 

更多命令能夠參考幫助:dotnet aspnet-codegenerator view -?

 

至此命令的展現也就完了。

dotnet aspnet-codegenerator 來源

那麼這個命令是從哪裏來的呢?dotnet 默認是沒有aspnet-codegenerator

 dependencies 節點添加以下:

  "dependencies": {
    ...
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    }
  },

而後在 tools 節點添加以下:

  "tools": {
    ...
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
      "version": "1.0.0-preview2-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

dotnet restore 

這樣也就可使用 dotnet aspnet-codegenerator 。

上面dotnet new 建立的web 項目可使用 dotnet aspnet-codegenerator ,是因爲項目默認已經給咱們添加了對應的節點及引用。

 

若是你是在Windows 下使用 VS 2015 開發的話,你將獲得更好的體驗。

使用 VS 2015 打開帶有dotnet aspnet-codegenerator的項目,VS 會自動擴展,新增額外添加功能。

在項目右鍵會發現多了添加 控制器,在Views 文件夾下右鍵,會多一個 添加 視圖。

選擇之後就能夠添加不一樣類型的Controller,這個其實也是調用dotnet aspnet-codegenerator 命令。

 

若是你以爲本文對你有幫助,請點擊「推薦」,謝謝。

相關文章
相關標籤/搜索