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


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

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

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

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

 

創建ASP.NET Core應用程序

dotnet new -t web

dotnet restore

dotnet run

 

創建好以后,我們來添加 Controller和View。

創建使用的dotnet命令為: dotnet aspnet-codegenerator

 

創建Controller

1.空白Controller

dotnet aspnet-codegenerator controller -name LineZero -outDir Controllers

2.增刪查改Controller

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

命令增加一個:-actions  

3.增刪查改+EF Controller

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

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

-m 指的是model

-dc 指 DbContext 

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 命令。

 

如果你覺得本文對你有幫助,請點擊“推薦”,謝謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM