Access to the global page variable in the helper
@{ int i = 0; } @helper Text() { <input type="text" name="Ans[@i].Text" /> } i not available in the assistant. How to get access to it?
You can simply add it as a member to your page using the @functions declaration :
@functions { private int i; } You can pass it as a parameter to the helper:
@helper Text(int i) { <input type="text" name="Ans[@i].Text" /> } and then:
@{ int i = 0; } @SomeHelper.Text(i) or you can just use editor templates that take care of everything and get rid of these helpers. For example:
@Html.EditorFor(x => x.Ans) You can achieve this by changing the base class for your view. This scenario applies to a situation where a helper is declared in sight.
Create a base class that inherits WebViewPage and introduces a common field or property:
public class MyBasePage<T> : WebViewPage<T> { public int i; public override void Execute() { } } Using the base class of the change @inherits directive. And now the field / property is available both from the "page context" and for the assistant:
@inherits NamespaceOfYourBaseClass.MyBasePage<YourModel> @{ i = 0; } @helper Text() { <input type="text" name="Ans[@i].Text" /> } If you want to have a thing close to the term "page property / field", but donβt want to create a base class, and helpers are stored in the App_Code folder, then you can try WebPageBase.Page .
MSDN Provides access to property-accessible data that is shared between pages, layout pages, and partial pages.
The code in this case will be:
@{ Page.i = 0; } @helper Text() { <input type="text" name="Ans[@Page.i].Text" /> } The disadvantage is that the Page property is of type dynamic and therefore does not support intellisense. As an alternative to Page there is another property - WebPageBase.PageData .
MSDN Provides access to data per page, accessible by type, layout pages, and partial pages.
In this case, a container class of string keys / ints can be created for "page variables". And the code will look like this:
// class visible to views and helpers class MyViewFields { public const string i = "MyViewFields.i"; // or maybe generate guid for key so there would be not doubts about its uniqueness.. but how would you debug this? :) } // in MyView.cshtml @{ PageData[MyViewFields.i] = 0 } @helper Text() { <input type="text" name="Ans[@PageData[MyViewFields.i]].Text" /> } This, at least, provides restrictions for shared page data, but does not control the type of value.