鍍金池/ 教程/ C#/ ASP.Net MVC視圖
ASP.Net MVC簡介
ASP.Net MVC過濾器
ASP.Net MVC視圖
ASP.Net MVC安全
ASP.Net MVC手腳架
ASP.Net MVC控制器
ASP.Net MVC與SQL Server數(shù)據(jù)庫操作
ASP.Net MVC NuGet包管理
ASP.Net MVC入門程序
ASP.Net MVC Razor
ASP.Net MVC Bootstrap
ASP.Net MVC單元測試
ASP.Net MVC動作
ASP.Net MVC模式
ASP.Net MVC選擇器
ASP.Net MVC開發(fā)環(huán)境配置
ASP.Net MVC生命周期
ASP.Net MVC模型綁定
ASP.Net MVC自托管(本地主機部署)
ASP.Net MVC驗證
ASP.Net MVC緩存
ASP.Net MVC數(shù)據(jù)模型
ASP.Net MVC路由
ASP.Net MVC教程
ASP.Net MVC助手
ASP.Net MVC數(shù)據(jù)注解
ASP.Net MVC Web API

ASP.Net MVC視圖

在ASP.NET MVC應用程序中,當在URL中指定路徑時,可像頁面那樣但不包含對應的任何內(nèi)容直接顯示給用戶。 在ASP.NET MVC應用程序中最接近頁面的東西就是視圖。

在ASP.NET MVC應用程序中,所有傳入的瀏覽器請求都由控制器處理,并將這些請求映射到控制器操作。 控制器操作可能會返回一個視圖,或者也可能執(zhí)行一些其他類型的操作,例如重定向到另一個控制器動作。

下面通過創(chuàng)建一個新的ASP.NET MVC項目,來演示如何應用視圖的簡單例子。
打開Visual Studio,然后單擊菜單:文件 -> 新建 -> 項目 選項。創(chuàng)建一個名稱為:MVCViewDemo 的MVC項目。

詳細創(chuàng)建過程請參考:http://www.yiibai.com/asp.net_mvc/asp.net_mvc_getting_started.html

通過在解決方案資源管理器 中右鍵單擊 Controllers 文件夾來添加一個控件器:HomeController。在彈出菜單項中選擇:添加 -> 控制器

將在Controllers文件夾中看到一個新的 C# 文件 - HomeController.cs,x在Visual Studio中打開并進行編輯。修改更新HomeController.cs文件中的代碼,其中包含兩個操作方法,如下面的代碼所示。

using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;
using System.Web.Mvc;

namespace MVCViewDemo.Controllers {
   public class HomeController : Controller{
      // GET: Home
      public ActionResult Index(){
         return View();
      }

      public string Mycontroller(){
         return "Hi, I am a controller";
      }
   }
}

運行這個應用程序,打開瀏覽器訪問:http://localhost:63461/Home/MyController,將收到以下輸出結果 -

由于MyController操作只是返回字符串,要從操作返回一個View,需要首先添加一個View。參考以下步驟 -

第1步: 在添加視圖之前,添加另一個操作,它將返回一個默認視圖。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCViewDemo.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        public string Mycontroller()
        {
            return "Hi, I am a controller";
        }

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

運行這個應用程序,并在瀏覽器的URL中添加http://localhost:63461/Home/MyView,然后按回車,將收到以下輸出。

在這里看到有一個錯誤,這個錯誤實際上是相當具有描述性的,告訴我們它找不到MyView視圖。

第2步 - 要添加一個視圖,右鍵單擊MyView動作(方法)并選擇添加視圖。如下圖所示 -

它將顯示“添加視圖” 對話框,并將添加默認名稱。

第3步 - 取消選中“使用布局頁面”復選框,然后單擊“添加”按鈕。現(xiàn)在新建的這個視圖內(nèi)有默認的代碼。如下所示 -

第4步 - 使用以下代碼在此視圖中添加一些文本。

@{
   Layout = null;
}

<!DOCTYPE html>
<html>
   <head>
      <meta name = "viewport" content = "width = device-width" />
      <title>MyView</title>
   </head>

   <body>
      <div>
         Hi, I am a view
      </div>
   </body>

</html>

第5步 - 運行該應用程序,并將打開瀏覽器訪問URL:http://localhost:63461/Home/MyView, 將收到以下輸出。