@ Helper helper method and @ functons UDF, @ Helper @ functons

Source: Internet
Author: User

@ Helper helper method and @ functons UDF, @ Helper @ functons

1. First, let's talk about the @ helper auxiliary method. When we use the same method in multiple views, we can strip this method out and put it in one location, in this case, you can use the @ Helper method. First, right-click the solution and add

App_Code folder, add a cshtml file, clear the content of the original file, and then put the custom method in it, for example

@ Helper Show (int I) {if (I = 1) {@: The value is 1} else {@: The value is other }}

2. When we want to implement more complex logic, for example, if we want to return a value, we can use the @ functions keyword to customize the function, as shown below:

@functions{public static IHtmlString GetYesterday()    {        var theDay = DateTime.Now.AddDays(-1);        return new HtmlString(theDay.ToString());    }}

Note that the static keyword must be used for modification in this place. Otherwise, this method cannot be called on other pages through the class, and the type of return value returned to the view must be defined as IHtmlString.

Supplement: When a new type is introduced to a page, the namespace may be too long, resulting in a lot of repeated code between pages. You can import the namespace at the beginning of the view page,

As follows: @ model IEnumrable <MVC. Test. Animal> can be changed

@ Using MVC. Test

@ Model IEnumrable <Animal>;

When the same namespace is introduced to all view pages, you can avoid using @ using to introduce each page. The view directory contains the web. config file.

The namespace used to add the <system. web. webPages. razor> section to each page is as follows:

<system.web.webPages.razor>    

 

Related Article

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.