MVC4 @helper Auxiliary method

Source: Internet
Author: User

Razor provides a convenient syntax for extracting portions of the View page or part of the code into an independent helper method.

EG1: @foreach (var item in Model) {< label tr>< label Td> @item. name</label td>< label td> @item. Price</label td></tag Tr>} When we want to the item. Price when processing, for example, 0 o'clock, the page display free, you need to add a judgment EG2: @foreach (var item in Model) {< label tr>< label Td> @item. name</label td>< label td> @if (item. price==0) { @: Free }else{ @item. Price }  </label Td></label Tr>} But if there are multiple fields to do so, then we can use Razor's @helper to take this part of the logic out, into a separate method, and @helper syntax is to add a method declaration behind the @helper, can contain some parameters , eg: @helper showprice (int price) {if (price==0) {@: Free}else{@price}} and then just call Eg3: @foreach (var item in Model) {< label tr> < label Td> @item. name</label td>< label td> @ShowPrice (item. Price)</label td></tag Tr> the syntax for declaring @helper helper methods is very similar to declaring methods in C #, the only difference being that no callbacks are made, and the default is Web page output. If you want to use this @helper helper method for several different view pages, consider independently of the project root App_Code, the standalone file suffix must be cshtml, as follows: Add an App_Code folder and add--New item--" MVC4 Layout Page This item is named uihelper.cshtml (preferably another name) and you can then move the @helper intact into the file, and then change it to @uihelper.showprice when we call it again. Price) can

MVC4 @helper Auxiliary method

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.