Using extension methods in MVC

Source: Internet
Author: User

Extension methods (Extension method) are a convenient way to add methods to classes that are not owned by you and thus cannot be modified directly.

1, define a shopping cart class-shoppingcart

1 usingSystem;2 usingSystem.Collections;3 usingSystem.Collections.Generic;4 usingSystem.Linq;5 usingsystem.web;6 7 namespaceDemo.models8 {9      Public classShoppingcart:ienumerable<product>Ten     { One          PublicList<product> Products {Get;Set; } -     } -}

2. Define an extension method

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingsystem.web;5 6 namespaceDemo.models7 {8      Public Static classMyextensionmethods9     {Ten          Public Static decimalTotalprices ( ThisShoppingCart Cartparam) One         { A             decimalTotal =0; -             foreach(Product prodinchcartparam.products) -             { theTotal + =Prod. Price; -             } -             returnTotal ; -         } -     } in}

The This keyword defines totalprices as an extension method ShoppingCart tells. NET this extension method applies to that class

3, the use of extension methods

1  PublicViewResult userextension ()2         {3             //Create and populate ShoppingCart4ShoppingCart cart =NewShoppingCart5             {6Products =NewList<product>{7                 NewProduct{name="Kayak", price=275m},//Kayaking8                 NewProduct{name="lifejacket", price=48.95M},//Casual Jackets9                 NewProduct{name="Soccer Ball", price=19.50M},//FootballTen                 NewProduct{name="Corner Flag", price=34.95M}//Corner Flag One                 } A             }; -             //find the total price of the product in the shopping cart -             decimal carttotal = cart. Totalprices (); the             returnView ("Result", (Object) String.Format ("Total:{0:c}", Carttotal)); -}

4. Results display

Using extension methods in MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.