1, first of all, say @helper auxiliary method, when we share the same method in multiple views, can be stripped out of this method to put in a position, at this time can use the @helper auxiliary method, first we in the solution right-click Add
App_Code folder, then add a cshtml file, empty the contents of the original file, and then put the custom method in it, for example
@helper Show (int i) { if(i==1) { @: value 1 } else { @: value is other }}
2, when we want to achieve more complex logic, such as to have a return value when you can use the @functions keyword to customize the function, as follows
@functions {publicstatic ihtmlstring getyesterday () { var Theday = DateTime.Now.AddDays (-1); return New htmlstring (theday.tostring ());} }
Note that this place must be decorated with the static keyword, otherwise the page cannot be called by the class, and the return value type returned to the view must be defined as ihtmlstring.
Add : When a new type is introduced into the page, the namespace may be very long, resulting in a lot of duplicate 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 to
@using MVC. Test
@model ienumrable<animal>;
When all view pages introduce the same namespace, there is a way to avoid each page to be introduced with @using, in the views directory there is a Web. config document, which can be found in this document
The <system.web.webPages.razor> section joins the namespaces that each page will use, as follows:
<system.web.webPages.razor> "System.Web.Mvc.MvcWebRazorHostFactory, SYSTEM.WEB.MVC, version=5.1.0.0, Culture=neutral, publickeytoken= 31bf3856ad364e35"/> <pages pagebasetype="System.Web.Mvc.WebViewPage"> <namespaces> <addnamespace="SYSTEM.WEB.MVC"/> <addnamespace="System.Web.Mvc.Ajax"/> <addnamespace="System.Web.Mvc.Html"/> <addnamespace="System.Web.Optimization"/> <addnamespace="System.Web.Routing"/> <addnamespace="WebApplication1"/> </namespaces> </pages> </system.web.webPages.razor>
@Helper helper methods and @functons custom functions