Introduction to Helpers
Introduction to Helpers
Helpers Fundamentals
Introduction
In traditional computer programming, a function is a section of code that performs a task. This means that a function is creating by writing C# code. When necessary, such a function can be called using the techniques we reviewed for calling a method of a class. To support an aspect of this concept of functions, ASP.NET MVC provides a feature called helper.
Practical Learning: Introducing Helpers
body { margin: 0px; background-color: white; } .container { width: 300px; margin: auto; }
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="~/Content/Site.css" /> <title>Binary Classification</title> </head> <body> <h2 style="text-align: center">Binary Classification</h2> </body> </html>
Creating a Helper
The primary formula to create a helper is:
@helper helper-name { }
Start with @ followed by helper (in lowercase). This is followed by a name for the helper. The name follows the rules of names of methods of a class. As seen for methods, the name of a helper is followed by parentheses and a body delimited by curly brackets.
To create a helper, you can include it in the HTML code of a webpage. This can be done as follows:
<!DOCTYPE html> <html> <head> <title>Exercise</title> </head> <body> <div> <h1>Exercise</h1> @helper Create(){ } </div> </body> </html>
Calling a Helper
After creating a helper, you can access it. This is referred to as calling a helper. To call a help, type @ followed by the actual name of the helper. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<h1>Exercise</h1>
@helper Create(){
}
<p>@Create()</p>
</body>
</html>
Values and Expressions in a Helper
In the body of a helper, you can use any type of constant or create any type of expression. Here is an example:
@{
248 + 8378;
}
The Contents of a Helper
HTML in a Helper
One of the fundamental differences between a method of a class and a helper is that a helper can contain HTML code. The HTML code is created exactly as done in any webpage.
Practical Learning: Creating a Helper
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="~/Content/Site.css" /> <title>Binary Classification</title> </head> <body> @helper Describe() { <div class="container"> <h3>Introduction</h3> <p> <b>Binary classification</b> is used in many areas of studies such as as social sciences (sociology, psychology, philosophy, etc), medecine, law, accounting, etc, to examine the likelihood of an event occurring or not occurring. </p> <h3>Binary classifination Table</h3> <p>Binary classifination can be resumed as follows:</p> <div align="center"> <table width="345" border="6"> <tr> <td> </td> <td style="font-weight: bold"><b>True</b></td> <td style="font-weight: bold">False</td> </tr> <tr> <td style="font-weight: bold">Positive</td> <td>True Positive</td> <td>False Positive</td> </tr> <tr> <td style="font-weight: bold">Negative</td> <td>False Negative</td> <td>True Negative</td> </tr> </table> </div> </div> } <h2 style="text-align: center">Binary Classification</h2> @Describe() </body> </html>
Variables in a Helper
You can declare one or more variables in the body of a helper. Here is an example:
@helper Declare(){
int number = 60358;
}
A variable declared in the body of a helper is referred to as a local variable. Such a variable can be used only in the helper. Of course, the local variable(s) can be involved in one or more expressions. Here is an example:
@helper Calculate() {
decimal ratio = 0;
decimal debt = 2227244;
decimal assets = 8101372;
ratio = debt / assets;
}
After declaring the variable, you can use it any way you want. To access the variable, precede its name with @. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<div>
<h1>Exercise</h1>
@helper Declare(){
int number = 60358;
<p>Number: @number</p>
}
<p>@Declare()</p>
</div>
</body>
</html>
You can initialize a local variable with any legal value, inclluding a value from a form created in the helper.
Practical Learning: Using Local Variables in a Helper
<!DOCTYPE html> <html> <head> <title>Depreciation - Straight-Line Method</title> </head> <body> @helper Evaluate() { decimal deprec = 0; decimal cost = 17000; decimal salvageValue = 2000; int estimatedLife = 5; if (IsPost) { cost = Request["txtCost"].AsDecimal(); salvageValue = Request["txtSalvageValue"].AsDecimal(); estimatedLife = Request["txtEstimateLife"].AsInt(); deprec = (cost - salvageValue) / estimatedLife; } <form name="frmDepreciation" method="post"> <table> <tr> <td width="120"><b>Machine Cost:</b></td> <td><input name="txtCost" type="text" value=@cost /></td> </tr> <tr> <td><b>Salvage Value:</b></td> <td><input name="txtSalvageValue" type="text" value=@salvageValue /></td> </tr> <tr> <td><b>Estimate Life:</b></td> <td><input name="txtEstimateLife" type="text" value=@estimatedLife /></td> </tr> <tr> <td> </td> <td><input name="btnCalculate" type="submit" value="Calculate" /></td> </tr> <tr> <td><b>Depreciation:</b></td> <td><input name="txtDepreciation" type="text" value=@deprec /></td> </tr> </table> </form> } <h3>Depreciation - Straight-Line Method</h3> @Evaluate() </body> </html>
Returning a Value from a Helper
A helper resembles a function in the sense that it always produces a value, whether you decide to use that value or not. A helper, that is, every helper, returns an object of a class named HelperResult. Behind the scenes, the compiler can assist you in returning a value of a primitive type. This means that you can make (convert the final value of) a helper return a string or a number.
To indicate the value that a helper returns, on the last line of the helper, before the closing curly bracket, type @ followed by the value. If the value is a constant, put it in pareentheses. Here are examples:
<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
@helper Itemize() {
@(748260);
}
@helper BuyIt() {
@(138.95);
}
@helper Wear() {
@("Petite Sleeveless Dress");
}
<p>Item #: @Itemize()</p>
<p>Item Name: @Wear()</p>
<p>Unit Price: @BuyIt()</p>
</body>
</html>
By the way, you can end the expression with a semicolon or you can omit the semicolon.
In the same way, if the value to return is from an expression, you can include that expression in parentheses after the @ symbol. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Business Processes</title>
</head>
<body>
@helper Calculate(){
decimal debt = 2227244;
decimal assets = 8101372;
@(debt / assets);
}
<p>Debt Ratio: @Calculate()</p>
</body>
</html>
If you want to return a variable, you can put the variable inside the parentheses or you can omit the parentheses. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Business Processes</title>
</head>
<body>
@helper Calculate(){
decimal ratio = 0;
decimal debt = 2227244;
decimal assets = 8101372;
ratio = debt / assets;
@ratio
}
<p>Debt Ratio: @Calculate()</p>
</body>
</html>
Passing Arguments to a Helper
Like a regular method, a helper can use parameter. To create a parameter, in the parentheses of the helper, specify a data type and a name for a parameter. If you want to use more than one parameter, separate them with commas.
When calling a helper that uses one or more parameters, you must provide a value for each parameter, in the same order they appear in the parentheses of the helper.
In the body of the helpr, if you are accessing an argument in a C# code, simply use its name. If you want to involve an argument in an HTML code, precede its name with @.
In this application, a not-for-profit (NFP) organization named OFRE (in this example, OFRE stands for Organization for Fund Raising Events) is in the business of raising money for various charities. An employee of OFRE calls a sollicittee to request an amount of money. A sollicittee can pledge to send a certain amount of money such as 1000, 2000, 5000, 10000, 200000, 1000000, etc. Then the caller requests the ratio by which that amount would be distributed between the selected charities. Examples of ratios are 1:2 (which is half), 3:2 (three to two), 5:2, etc. |
Practical Learning: Passing Arguments to a Helper
body { padding-top: 50px; padding-bottom: 20px; } #glued-part { top: 0; width: 100%; height: 75px; position: fixed; background-color: white; border-bottom: 2px solid maroon; } .font-format { margin-top: 0; font-weight: 800; font-family: Cambria, Cochin, Georgia, Times, Times New Roman, serif; } .heading1 { color: maroon; font-size: 2.12em; line-height: 1.75em; } .heading2 { color: #b71f1f; font-size: 1.32em; line-height: 1.15em; } .contents { width: 300px; margin: auto; margin-top: 40px; } .left-column { width: 140px; } .tbx-format { width: 50px; } .text-center { text-align: center; }
<CTYPE html> <html> <head> <title>Organization for Fundraising Events</title> <link href="~/Content/Site.css" type="text/css" rel="stylesheet" /> </head> <body> @helper DistributePart1(decimal amount, int portion1, int portion2) { int totalRatios = portion1 + portion2; decimal eachPart = amount / totalRatios; decimal result = eachPart * portion1; @result } @helper DistributePart2(decimal amount, int portion1, int portion2) { int totalRatios = portion1 + portion2; decimal eachPart = amount / totalRatios; decimal result = eachPart * portion2; @result } @{ decimal amount = 0; int ratio1 = 1; int ratio2 = 1; if (IsPost) { amount = Request["txtAllocation"].AsDecimal(); ratio1 = Request["txtPortion1"].AsInt(); ratio2 = Request["txtPortion2"].AsInt(); } } <div id="glued-part"> <p class="heading1 text-center font-format">Organization for Fundraising Events</p> </div> <div class="contents"> <p class="heading2 text-center font-format">Pledge Distribution</p> <form name="frmDistribution" method="post"> <table> <tr> <td class="left-column">Amount to Allocate:</td> <td><input type="text" name="txtAllocation" value=@amount class="tbx-format" /></td> </tr> </table> <table> <tr> <td class="left-column">In the Ratio:</td> <td><input type="text" name="txtPortion1" class="tbx-format" value=@ratio1 /></td> <td>:</td> <td><input type="text" class="tbx-format" name="txtPortion2" value="@ratio2" /></td> <td><input name="btnAllocate" type="submit" value="Allocate" /></td> </tr> </table> <hr /> <table> <tr> <td class="left-column">Part 1 Receives:</td> <td><input type="text" name="txtPart1" value=@DistributePart1(@amount, @ratio1, @ratio2) /></td> </tr> <tr> <td>Part 2 Receives:</td> <td><input type="text" name="txtPart2" value="@DistributePart2(@amount, @ratio1, @ratio2)" /></td> </tr> </table> </form> </div> <hr /> <footer> <p class="text-center">© @DateTime.Now.Year :: Organization for Fundraising Events</p> </footer> </body> </html>
Amount to Allocate: 6540 Portion 1: 5 Portion 2: 3
Creating Many Helpers in the Same File
You can create as many helpers are you want in a file. The helpers must follow the rules we saw for methods of a class. This means that each method must have a syntax different from the other helpers in the same file. If you want to use the same name on more than one helper, you must apply the rules of overloading. This means that either the methods with the same name have different numbers of parameters or their parameters are of different types. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
@helper Calculate()
{
}
@helper Calculate(decimal a)
{
}
@helper Calculate(decimal a, int b)
{
}
</body>
</html>
A Helper with Optional Parameters
When creating a parameter for a helper, you can give a default value to the paramete. This is done by assigning a default value to the parameter. Here is an example:
@helper Calculate(decimal a = 0)
{
}
Other than, everything is done as we reviewed the concept for methods whose parameters have default values.
Helpers and Classes
An Object in a Helper
As seen for variables of primitive types, in the body of a helper, you can create an object of a class and use that object locally any way you want.
Practical Learning: Using an Object Local to a Helper
body { margin: 0; background-color: #FFFFFF; } .container { margin: auto; width: 375px; } .small-area { width: 50px; }
public class Territory { public string TerritoryName { get; set; } public decimal Area { get; set; } public string Capital { get; set; } }
<!DOCTYPE html> <html> <head> <title>Countries Statistics</title> <link rel="stylesheet" type="text/css" href="~/Content/Site.css" /> </head> <body> @helper StartUnion() { Territory ter = new Territory(); ter.TerritoryName = "Yukon"; ter.AreaLand = 474391; ter.AreaWater = 8052; ter.Capital = "Whitehorse"; int totalArea = ter.AreaLand + ter.AreaWater; <div class="container"> <form name="frmStates" method="post"> <table> <tr> <td><b>Territory Name:</b></td> <td><input value="@ter.TerritoryName" type="text" name="txtTerritoryName" /></td> </tr> <tr> <td><b>Land Area:</b></td> <td><input type="text" name="txtArea" value=@ter.AreaLand /> km<sup>2</sup></td> </tr> <tr> <td><b>Water Area:</b></td> <td><input type="text" name="txtArea" value=@ter.AreaWater /> km<sup>2</sup></td> </tr> <tr> <td><b>Total Area:</b></td> <td><input type="text" name="txtArea" value=@totalArea /> km<sup>2</sup></td> </tr> <tr> <td><b>Capital:</b></td> <td><input type="text" name="txtCapital" value="@ter.Capital" /></td> </tr> </table> </form> </div> } h2 style="text-align: center">Countries Statistics - Canada</h2> @StartUnion() </body> </html>
Passing an Object to a Helper
A parameter of a helper can be an object of a class type. When creating the parameter, you must appropriately specify its type using the name of a class. In the body of the helper, you can use or ignore the parameter.
Practical Learning: Using a Parameter of a Class Type in a Helper
<!DOCTYPE html> <html> <head> <title>Countries Statistics</title> <link rel="stylesheet" type="text/css" href="~/Content/Site.css" /> </head> <body> @helper StartUnion(Territory ter) { int totalArea = ter.AreaLand + ter.AreaWater; <div class="container"> <form name="frmStates" method="post"> <table> <tr> <td><b>Territory Name:</b></td> <td><input value="@ter.TerritoryName" type="text" name="txtTerritoryName" /></td> </tr> <tr> <td><b>Land Area:</b></td> <td><input type="text" name="txtArea" value=@ter.AreaLand /> km<sup>2</sup></td> </tr> <tr> <td><b>Water Area:</b></td> <td><input type="text" name="txtArea" value=@ter.AreaWater /> km<sup>2</sup></td> </tr> <tr> <td><b>Total Area:</b></td> <td><input type="text" name="txtArea" value=@totalArea /> km<sup>2</sup></td> </tr> <tr> <td><b>Capital:</b></td> <td><input type="text" name="txtCapital" value="@ter.Capital" /></td> </tr> </table> </form> </div> } <h2 style="text-align: center">Countries Statistics - Canada</h2> @{ Territory can = new Territory(); can.TerritoryName = "Northwest Territories"; can.AreaLand = 1183085; can.AreaWater = 163021; can.Capital = "Yellowknife"; } @StartUnion(can) </body> </html>
Global Helpers
Introduction
ASP.NET MVC supports two approaches to creating a helper. As seen since our introduction, one technique is to create a helper in the contents of a weppage's code. That technique has the limitation that such a helper can be accessed only in that webpage. If you want a helper that can be accessed by any webpage of your website, ASP.NET provides the ability to create a special file whose name behaves like a static class. In reality, you would create a code file that resembles a document that contains a class without explicitly containing a class. In the file, you can then create one or more helpers that are considered global within the project.
Creating a Helper File
A helper file is a text-based Razor file that has the extension .cshtml. You can create the file using any text editor.
To help you create a special static class for one or more helpers, display the Add New Item dialog box. From the Razor group, in the middle list, click Helper (Razor v3). Accept or change the name of the file. After creating a helper file, you can populate it with code as we have done so far.
Practical Learning: Adding a Property to an Interface
@helper Calculate(decimal a, decimal b, decimal c) { @(a * (b + c)) } @helper EvaluateRateAmount(decimal original, decimal increaseRate = 0) { @(original * increaseRate / 100); }
Calling a Global Helper
A helper from a helper file is called like a method from a static class. That is, type the name of the file, a period, and the name of the helper. Other than that, follow the rules of calling a method in terms of arguments and return values.
Practical Learning: Calling a Global Helper
<!DOCTYPE html> <html> <head> <title>Department Store - Inventory</title> </head> <body> <h2>Department Store - Inventory</h2> @{ decimal unitPrice = 0; decimal discountRate = 0; if (IsPost) { unitPrice = Request["txtUnitPrice"].AsDecimal(); discountRate = Request["txtDiscountRate"].AsDecimal(); } } <form name="frmInventory" method="post"> <table> <tr> <td>Unit Price:</td> <td><input type="text" name="txtUnitPrice" value=@unitPrice /></td> </tr> <tr> <td>Discount Rate:</td> <td><input type="text" name="txtDiscountRate" value=@discountRate /> %</td> </tr> <tr> <td> </td> <td><input type="submit" name="btnCalculate" value="Calculate" /></td> </tr> <tr> <td>Discount Amount:</td> <td><input type="text" name="txtDiscountAmount" value=@Accessories.EvaluateRateAmount(@unitPrice, @discountRate) /></td> </tr> </table> </form> </body> </html>
<!DOCTYPE html> <html> <head> <title>Department Store - Time Worked</title> </head> <body> <h2>Department Store</h2> <h3>Time Worked Evaluation</h3> @{ decimal week1 = 0.00m; decimal week2 = 0.00m; decimal salary = 0.00m; if (IsPost) { salary = Request["txtHourlySalary"].AsDecimal(); week1 = Request["txtWeek1"].AsDecimal(); week2 = Request["txtWeek2"].AsDecimal(); } } <form name="frmTimeWorked" method="post"> <table> <tr> <td>Hourly Salary:</td> <td><input type="text" name="txtHourlySalary" value=@salary /></td> </tr> <tr> <td>Time Worked in Week 1:</td> <td><input type="text" name="txtWeek1" value=@week1 /></td> </tr> <tr> <td>Time Worked in Week 2:</td> <td><input type="text" name="txtWeek2" value=@week2 /></td> </tr> <tr> <td> </td> <td><input type="submit" name="btnCalculate" value="Calculate" /></td> </tr> <tr> <td>Biweekly Salary:</td> <td><input type="text" name="txtBiweeklySalary" value=@Accessories.Calculate(@salary, @week1, @week2) /></td> </tr> </table> </form> </body> </html>
|
||
Previous | Copyright © 2003-2019, FunctionX | Next |
|