MVC4 學習筆記01

來源:互聯網
上載者:User

標籤:des   blog   http   使用   檔案   資料   

1 、 ASP.NET MVC 中 ActionResult 和 ViewResult 在使用上的區別是什嗎?要注意什麼嗎? ActionResult 是一個抽象(abstract)類,ViewResult 只是ActionResult 的一個實現(implementation)。如果你確認你返回的是一個視圖(view),你可以直接傳回型別為ViewResult。ActionResult 有很多的衍生類別,如果你很確定你要返回的類型,你可以明確的返回該類型。如果你並不是很清楚,或者你根本不想去理解這些東西,你可以直接返回這些衍生類別的基類:ActionResult 。 ActionResult :http://msdn.microsoft.com/zh-cn/library/system.web.mvc.actionresult.aspx  ViewResult:http://msdn.microsoft.com/zh-cn/library/system.web.mvc.viewresult.aspx

2、viewbag viewdata http://www.cnblogs.com/wintersun/archive/2012/01/21/2328563.html 本質:viewbag  是 dynamic(動態類型)  viewdata  是索引值對

3、 強型別視圖(就是引用模型類)比弱類型視圖多了 @model Partylnvites.Models.GuestResponse 還可以再建立視圖的時候 使用內建的 create 、edit  模板,它會自動產生代碼

4、視圖 頁面 添加控制項 ,@html.textboxfor 、Html.DropDownListFor  @using (Html.BeginForm())  編譯之後變成 <form action="/Home/TestView" method="post">   5、 在 Homecontrol 代碼檔案 添加 模型引用 using Partylnvites.Models;  6、  return View()  view 裡面有很多重載 在 control 方法 上夾   [HttpGet] [HttpPost] 區分了 form 的method,不同功能的視圖結果 7、增加驗證  在 模型類 增加using System.ComponentModel.DataAnnotations; 裡面類的 的屬性 上方 [Required(ErrorMessage = "Please enter your name")]  但還需要 在 方法裡面判斷if (ModelState.IsValid)   ,在 view 裡面 的 form 裡面 加上@Html.ValidationSummary()  才能 顯示出  ErrorMessage 類容 ,編譯之後 就是個div <div class="validation-summary-errors" data-valmsg-summary="true"><ul><li>Please enter your name</li>   </ul></div>         當你輸入錯誤的時候 提交 返回的 input 標籤變成了 <input class="input-validation-error" data-val="true" data-val-required=">Please enter your name" id="Name" name="Name" type="text" value="" /> 這為我們就好顯示輸入錯誤 文字框的樣式

8 、private set; public int ItemID { get; private set; } // The unique key     private set; 表示唯讀 http://bbs.csdn.net/topics/250016321

9、MVC 模式  request-control-model-資料庫-model-control-view-response

10、  return View( view檔案名稱(字串),object)  object 一般會傳入 一個model ,但這裡定義object ,也可以傳入 任意類型 比如說: (object)string.Format("Pname is {0}", names) 這裡只傳入 這個模型的使用者名稱,那麼 在 view 的代碼怎麼寫呢?傳入模型時 @model Partylnvites.Models.GuestResponse  ,現在只使用者名稱了 所以 也可以 @model String  ,這就能理解view跟 控制器之間的傳值關係了。

11、Product myProduct = new Product { ProductID = 100, Name = "Kayak", Description = "A boat for one person", Price = 275M, Category = "Watersports" };  習慣像這樣簡寫

12、關於 IEnumerable      public class ShoppingCart02:IEnumerable<Product>     {         public List<Product> Products { get; set; }         public IEnumerator<Product> GetEnumerator()         {             return Products.GetEnumerator();         }

        IEnumerator IEnumerable.GetEnumerator()         {             return GetEnumerator();         }     } 因為 List<> 提供了 GetEnumerator 方法,所以這裡可以直接用

13、程式集 和 命名空間是多對多的關係 14、 擴充方法:   this 的使用 this 關鍵字 作為 擴充方法 ,擴充方法在靜態類中聲明,定義一個靜態方法,為了區分擴充方法和一般的靜態方法,擴充方法還需要給第一個參數使用this關鍵字,多個類可以使用相同的實現代碼(初步認為是 當 這個類已經被封裝了,沒有原始碼了,可以這樣給它增加功能) public static class MyExtensionMethods { public static decimal TotalPrices(this ShoppingCart cartParam) { decimal total = 0; foreach (Product prod in cartParam.Products) { total += prod.Price; } return total; } } 15、擴充方法在介面中的使用     public class ShoppingCart02:IEnumerable<Product>     {         public List<Product> Products { get; set; }         public IEnumerator<Product> GetEnumerator()         {             return Products.GetEnumerator();         }

        IEnumerator IEnumerable.GetEnumerator()         {             return GetEnumerator();         }     }

繼承 IEnumerable 範型介面 在 一個 靜態類中         public static decimal TotalPrices02(this IEnumerable<Product> Pro)         {             decimal Dtemp = 0;             foreach (Product prod in Pro)             {                 Dtemp += prod.Price;             }             return Dtemp;         } 在外部調用 IEnumerable<Product> pros = new ShoppingCart02()             {                 Products = new List<Product>{                    new Product(){                        Price=1                    }                }             };   pros.TotalPrices02(); 16、在過濾器中使用  擴充方法 (發現這是好方法!) 在 一個 靜態類中         public static IEnumerable<Product> FilterByname(this IEnumerable<Product> Pro, string name)         {             foreach (Product P in Pro)             {                 if(P.Name==name){                     yield return P;                 }             }         } 在外部調用             IEnumerable<Product> Pros02 = new ShoppingCart02()             {                 Products = new List<Product>{                     new Product(){Name="s",Price=10},new Product(){Name="s",Price=20},new Product(){Name="ss",Price=11}                 }             };          IEnumerable<Product>  PS=     Pros02.FilterByname("s"); 使用羅曼達運算式  用委託 (我認為目的在於架構師提供 fill 功能,具體規則 程式員寫) 在 一個 靜態類中         public static IEnumerable<Product> Filter(this IEnumerable<Product> Pro, Func<Product, bool> selectorParam)         {             foreach (Product P in Pro)                {                 if (selectorParam(P))                     yield return P;             }         } 在外部調用             Func<Product, bool> Fundel = delegate(Product P)             {                 return P.Name == "a";             };             decimal Total = 0;             foreach ( Product P in PS.Filter(Fundel) ){                 Total += P.Price;             } 這裡就不在局限於 過濾nane 屬性了

委託也可以簡寫為 羅曼達運算式  Func<Product, bool> Funlomanda = P => P.Name == "s"; 所以 也直接可以簡寫為  foreach (Product item in PS.Filter(P => P.Name == "s")) 17、使用Linq             var Result = Proarr.OrderByDescending(e => e.Price)                 .Take(1)                 .Select(e => new {                     e.Price, e.Name }); 按Price 排序 ,取 top 1

18、注意  Product[] Proarr = { new Product() { Name = "bing", Price = 1 }, new Product() { Name = "CC", Price = 2 }, new Product() { Name = "CC", Price = 12 } };             var Result = Proarr.OrderByDescending(e => e.Price)                 .Take(1)                 .Select(e => new {                     e.Price, e.Name });// 執行完 上面代碼 Result  結果 是 Name = "CC", Price = 12

            Proarr[2] = new Product() { Name = "bingt1", Price = 22 };//但是執行這個卻會改變 Result 的結果  ,最後變成了Name = "bingt1", Price = 22

但是  如果 不做  OrderByDescending 操作 ,改為   var Result = Proarr.Sum(e => e.Price); 最終Result  卻不會發生改變 這個需要參照對照表  第 90 頁 的Deferred

19、使用非同步 Using Async Methods   //沒明白 using System.Net.Http; using System.Threading.Tasks; public class MyAsyncMethod     {         public static Task<long?> GetPageSize()         {             HttpClient client = new HttpClient();             var httpTask = client.GetAsync("http://apress.com");             return httpTask.ContinueWith((Task<HttpResponseMessage> antecedent) =>             {                 return antecedent.Result.Content.Headers.ContentLength;             });

        }

        public async static Task<long?> GetPageLength()         {

            HttpClient client = new HttpClient();             var httpMessage = await client.GetAsync("http://apress.com");             // we could do other things here while we are waiting             // for the HTTP request to complete             client.GetAsync("http://apress.com");             // we could do other things here while we are waiting             // for the HTTP request to complete             return httpMessage.Content.Headers.ContentLength;         }     }

20、Razor 學習 使用強型別 @model  M 大寫  與小寫 是有區別的

21、Layout 主版頁面  @RenderBody()  代表它的子頁面

22、Razor 視圖 可以直接引用  @using Razor.Models

23、Ninject  沒明白 128 頁 意思就是面向介面 http://www.cnblogs.com/haogj/archive/2013/05/01/3053171.html using Ninject;

IKernel ninjectKernel = new StandardKernel();    執行個體化對象 ninjectKernel.Bind<IValueCalculator>().To<LinqValueCalculator>();   綁定 介面和 類 IValueCalculator calc = ninjectKernel.Get<IValueCalculator>(); ShoppingCart cart = new ShoppingCart(calc) { Products = products }; decimal totalValue = cart.CalculateProductTotal(); return View(totalValue);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.