asp.net MVC @Helper helper methods and the use of @functons custom functions _ Practical Tips

Source: Internet
Author: User
Tags html tags

The ASP.net Razor view has a. cshtml suffix that enables easy switching of C # code and HTML tags, greatly enhancing our development efficiency. But the razor grammar still has some marshmallows. We can learn more about how to improve our development efficiency and reduce the development bug.

Razor is using the @ tail symbol, which is the symbol of the development efficiency of MVC improvement. Here are two reusable helper and functions that are related to @.

As a modern programmer, we follow a principle as much as possible. Don't repeat yourself. So the code that can be refactored we all merge, but this is in the background code C #, for the view layer can also do some simple business logic, of course, the view layer can carry out complex business logic judgment, but the predecessor said that the complex business logic is model or controller work, The view layer's task is to show that the business logic should be as small as possible.

What are some of the refactorings in the view layer? One of these is the @helper custom fragment.

For example, if we want to output a number, if 0 of the output does not exist, if the output for other numbers exist, of course, this in the strong razor syntax can easily be done.

@ (viewbag.isenabled = "0"?) "Does not exist": "Exist")

But what if the current page has many of these same logical judgments? Smart programmers must know that you can't repeat your principles, so we're going to refactor, but how do we refactor at the view level? Using @helper can solve this problem.

@helper Show (int count)
{
  if (count = 0)
  {
    @: exists
  }
  else
  {
    @: does not exist}
}

@ (viewbag.isenabled = 0?) "Does not exist": "Exist")
@Show (0) @* call helper*@

So we are in the current page of multiple locations to the output, if you want to modify the part can be modified, but not all to modify.

And I'm going to say, what do I do with this helper on other pages? Of course, there is a way, add a view file under the App_Code folder (assumed to be uihelper.cshtml), copy the helper code, and then call it through @uihelper.show (0) on the view page that needs to be invoked. Because the files under the App_Code folder will eventually be compiled into classes.

Summary: We summarize how many ways to achieve the output according to different circumstances, of course, I can think of is not complete.

1. Use the helper to make a global setting so that all the pages that need to be judged call this helper method.
2. In the background code to judge, and then output to the foreground view.
3. Through the Html.action () or html.partial () to obtain, of course, if the simple or the use of helper, complex can be used in this way.
4. Implemented by custom function functions.

Custom Function @functions, the custom function uses C # syntax to implement code reuse, except that this function can output HTML tags to the page.

Custom Function @functions
@functions {public
  ihtmlstring get (int count)
  {string result
    = ' ";
    if (count = = 0)
    {result
      = "does not exist";
    }
    else
    {result
      = "exist";
    }
    return new htmlstring (result);
  }


@Get (0)  //invoked custom function

Note that the @functions corresponds to the Razor code snippet, which needs to be added {}, and functions internal is the normal C # method.

If you want to use this functions on multiple pages at the same time, you can migrate this method into App_Code, assuming the file name is uihelper.cshtml. And the method inside must be defined as static. This is well understood, the uihelper is equivalent to the class name, and the functions is equivalent to the method, and if you want to invoke it by the class name. 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
      = "does not exist";
    }
    else
    {result
      = "exist";
    }
    return new htmlstring (result);
  }

Summary:The helper is for the direct output of HTML content and has simple logic, and the helper does not have any return value, while the functions custom function is much more powerful, if the functions need to return HTML content, The return value is the ihtmlstring type and can be set to void if no return value is required, but if there is no return value it loses the meaning of the definition function, so the general return value is ihtmlstring. For the refactoring of the view layer, we can implement it using helper and custom function functions.

add: When introducing new types in a page, it is possible that namespaces are long, resulting in a lot of duplicate code between pages, where you can import namespaces 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 namespaces, you can take a way to avoid each page using @using to introduce, in the views directory has a Web.config document, you can under this document

The namespaces that the <system.web.webPages.razor> section will use to add to each page are 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.