標籤:des style blog http io color ar os sp
周末狂歡兩天,這周工作任務又好多,幾天沒有學習。。。
一、控制器和動作:
從前面的內容我們可以看到控制器的動作基本有兩個特點:(1)public修飾;(2)返回ActionResult。
但動作並非必須返回ActionResult,可以是void的或其他,如下面兩例:
1 public class SimpleController:Controller 2 { 3 public void Index() 4 { 5 Response.Write("<h1>Hello World !</h1>"); 6 } 7 } 8 ////////////////////////////////////////////////////////////// 9 public class SimpleController:Controller10 {11 public string Index()12 {13 return "<h1>Hello World !</h1>";14 } 15 }
需要注意的是ControllerActionInvoker(控制器動作調用器)總是將動作的傳回值封裝成一個ActionResult。
另外,我們可以用NoActionAttribute對public方法進行修飾,以阻止控制器上的public方法成為動作:
1 public calss SimpleController:Controller2 {3 [NoAction]4 public string SomePublicMethod()5 {6 return "Hello Wordl !";7 }8 }
二、控制器的任務:
控制器有兩個通用任務:手工映射視圖模型和接受使用者輸入(執行驗證)。
1.手動映射視圖模型:
視圖模型是為了在螢幕上顯示資料而單獨建立的模型對象。隨著應用程式複雜性的提升,往往要求視圖資料與模型結構不同。例如Guestbook應用程式的一個頁面中顯示每個使用者的評論次數:
1)添加一個視圖模型:
1 namespace Guestbook.Models2 {3 public class CommentSummary4 {5 public string UserName { get; set; }6 public int NumberOfComments { get; set; }7 }8 }
2)控制器添加動作:
1 public ActionResult CommentSumary() 2 { 3 var entries = from entry in db.Entries 4 group entry by entry.Name 5 into groupByName 6 orderby groupByName.Count() descending 7 select new CommentSummary 8 { 9 NumberOfComments=groupByName.Count(),10 UserName=groupByName.Key11 };12 return View(entries.ToList());13 }
3)添加視圖:
1 @model IEnumerable<Guestbook.Models.CommentSummary> 2 3 @{ 4 ViewBag.Title = "CommentSumary"; 5 } 6 7 <h2>CommentSumary</h2> 8 9 <p>10 @Html.ActionLink("Create New", "Create")11 </p>12 <table class="table">13 <tr>14 <th>15 @Html.DisplayNameFor(model => model.UserName)16 </th>17 <th>18 @Html.DisplayNameFor(model => model.NumberOfComments)19 </th>20 <th></th>21 </tr>22 23 @foreach (var item in Model) {24 <tr>25 <td>26 @Html.DisplayFor(modelItem => item.UserName)27 </td>28 <td>29 @Html.DisplayFor(modelItem => item.NumberOfComments)30 </td>31 </tr>32 }33 34 </table>View Code
2.輸入驗證:
前面GuestbookController的Create動作中接受使用者輸入沒有做任何驗證,下面加以改進:
1)添加驗證註解屬性--修改GuestbookEntry:
1 namespace Guestbook.Models 2 { 3 public class GuestbookEntry 4 { 5 public int Id { get; set; } 6 [Required] 7 public string Name { get; set; } 8 [Required] 9 public string Message { get; set; }10 public DateTime DateAdded { get; set; }11 }12 }
2)檢查驗證是否成功--修改create動作:
1 [HttpPost] 2 [ValidateAntiForgeryToken] 3 public ActionResult Create([Bind(Include="Id,Name,Message,DateAdded")] GuestbookEntry guestbookentry) 4 { 5 if (ModelState.IsValid)//檢查驗證是否成功 6 { 7 db.Entries.Add(guestbookentry); 8 db.SaveChanges(); 9 return RedirectToAction("Index");10 }11 12 return View(guestbookentry);//失敗時重新渲染表單13 }
3)在視圖中顯示錯誤訊息:
@Html.ValidationSummary(true)
註:若要在視圖中顯示自訂訊息,只要修改Required註解屬性的聲明,如:
[Required(ErrorMessage="請輸入您的使用者名稱")] public string Name { get; set; }
如果不想對訊息進行寫入程式碼,可以指定源檔案的名稱和類型:
[Required(ErrorMessageResourceType=typeof(類型), ErrorMessageResourceName=名稱]
不知道是網路還是部落格園出了問題,丟失了部分內容,剩下的重新整理單獨再發一篇吧。。。
《ASP.NET MVC 4 實戰》學習筆記 4:控制器(上)