How to use ASP. NET MVC @ Helper helper methods and @ functons custom functions

  • 2021-07-16 02:16:47
  • OfStack

The ASP. NET Razor view has the. cshtml suffix, which makes it easy to switch between c # code and html tag, greatly improving our development efficiency. However, there are some marshmallows worth knowing about Razor syntax, which can improve our development efficiency and reduce the emergence of bug.

Razor uses the @ tail symbol, which improves the development efficiency of MVC. Learn about two reusable helper and functions related to @ under 1.

As modern programmers, we try our best to abide by one principle. Don't repeat yourself. Therefore, we will merge the codes that can be reconstructed, but this is for the background code C #. For the View layer, we can also carry out some simple business logic. Of course, the View layer can carry out complex business logic judgment, but the predecessors said that complex business logic is the work of Model or Controller, and the task of View layer is to show that the less business logic, the better.

What are the 1 refactoring done at the View layer? One of them is the @ helper custom fragment.

For example, if we want to output a number, if it is 0, the output does not exist, and if it is other numbers, the output exists. Of course, this can be easily done under the powerful Razor syntax.


@(ViewBag.IsEnabled == "0" ? " Nonexistent " : " Existence ")

But what if the current page has many such same logical judgments? Smart programmers certainly know that you can't repeat your own principles, so we have to refactor, but how to refactor in View layer? Use @ helper to solve this problem.


@helper Show(int count)
{
  if (count == 0)
  {
    @: Existence 
  }
  else
  {
    @: Nonexistent 
  }
}

@(ViewBag.IsEnabled == 0 ? " Nonexistent " : " Existence ")
@Show(0)    @* Call helper*@

In this way, we call the output at multiple positions on the current page. If you want to modify it, you can modify part 1 instead of all.

And just to say, what should I do if I want to use this helper on other pages? Of course, there is still a way. Add a view file under the app_code folder (assuming UIHelper. cshtml), copy the helper code, and then call it through @ UIHelper. Show (0) on the View page that needs to be called. Because the files in the app_code folder will eventually be compiled into classes.

Summary: We summarize 1 to achieve output according to different situations how many ways to achieve, of course, I can think of not completely.

1. Through the helper global settings, so that all the need to judge the page call this helper method.
2. In the background code judgment, and then output to the foreground View.
3. Get it through Html. Action () or Html. Partial (). Of course, if helper is used for simple ones, it can be used in this way for complex ones.
4. It is realized by custom function Functions.

Custom function @ functions, custom function uses c # syntax to achieve code reuse, but this function can output html tags to the page.


// Custom function @functions
@functions{
  public IHtmlString Get(int count)
  {
    string result = "";
    if (count == 0)
    {
      result = " Nonexistent ";
    }
    else
    {
      result = " Existence ";
    }
    return new HtmlString(result);
  }
}


@Get(0)  // Custom function called 

Note that @ functions corresponds to the code snippet of Razor, you need to add {}, and inside functions is the regular c # method.

If you want to use this functions on multiple pages at the same time, you can port this method to app_code, assuming the file name is UIHelper. cshtml. And the methods inside must be defined as static. This is easy to understand. UIHelper is equivalent to the class name, and functions is equivalent to the method. If you want to call by the class name and method name, you must define the method as static.

UIHelper. cshtml file code


@helper ShowUnit(int count)
{
  if (count == 0)
  {
    @: Free 
    }
  else
  {
    @count
  }
}

@functions {
  public static IHtmlString Check(int count)
  {
    string result = "";
    if (count == 0)
    {
      result = "fsdfsdfsdfd";
    }
    else
    {
      result = count.ToString();
    }
    return new HtmlString(result);
  }
}
// Custom function @functions
@functions{
  public static IHtmlString Get(int count)
  {
    string result = "";
    if (count == 0)
    {
      result = " Nonexistent ";
    }
    else
    {
      result = " Existence ";
    }
    return new HtmlString(result);
  }
}

Summary: helper is for the case where html content is directly output and has simple logic. And helper does not have any return value, while functions custom function is much more powerful. If functions needs to return html content, the return value is IHtmlString type, and if it does not need a return value, it can be set to void, but if there is no return value, it will lose the meaning of defining function, so all the return values are IHtmlString. For the reconstruction of View layer, we can use helper and custom function functions to realize it.

Add: When you introduce a new type into a 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.

Below: @ model IEnumrable < MVC.Test.Animal > It can be changed to

@using MVC.Test

@model IEnumrable < Animal > ;

When all view pages will introduce the same namespace, you can take one way to avoid using @ using to introduce each page. There are web. config documents in Views directory, which can be found in

< system.web.webPages.razor > Section adds the namespace used by each page, as follows:


<system.web.webPages.razor>
  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
   <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="WebApplication1" />
   </namespaces>
  </pages>
</system.web.webPages.razor>

Related articles: