Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

c# - What does an @functions code block in a razor file do, and when (if ever) should I use it?

Whilst looking at a theme I downloaded from the Orchard CMS gallery, I noticed that a Layout.cshtml file had this block of code at the top of the file:

@functions {
// To support the layout classifaction below. Implementing as a razor function because we can, could otherwise be a Func<string[], string, string> in the code block following.
string CalcuClassify(string[] zoneNames, string classNamePrefix)
{
    var zoneCounter = 0;
    var zoneNumsFilled = string.Join("", zoneNames.Select(zoneName => { ++zoneCounter; return Model[zoneName] != null ? zoneCounter.ToString() : ""; }).ToArray());
    return HasText(zoneNumsFilled) ? classNamePrefix + zoneNumsFilled : "";
}
}

I know what the declared function does (calculates which zones are populated in order to return the width of each column), my question is- what is the correct use of the @function block, and when should I ever use it?

question from:https://stackoverflow.com/questions/13975290/what-does-an-functions-code-block-in-a-razor-file-do-and-when-if-ever-should

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The @functions block lets you define utility functions directly in the view, rather than adding them as extensions to the @Html helper or letting the controller know about display properties. You'd want to use it when you can meet these conditions:

  1. The functionality is tied closely to the view and is not generally useful elsewhere (such as "How wide do I make my columns").
  2. The functionality is more than a simple if statement, and/or is used in multiple places in your view.
  3. Everything that the function needs to determine it's logic already exists in the Model for the view.

If you fail the first one, add it as a @Html helper.

If you fail the second one, just inline it.

If you fail the third one, you should do the calculation in your controller and pass the result as part of the model.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...