Objects and Collections
Page Objects
The most basic object in ASP.NET is the page. You can access properties of the page object directlywithout any qualifying object. The following code gets the page's file path, using the Request object of the page:
@{var path = Request.FilePath;}
@path
@{
var pageUrl = this.Request.Url;
}
<br />
<a href="@pageUrl">My page</a>
/Helper/Objects
My page
Collection Objects (Arrays and Dictionaries)
@{
<h3>Team Members</h3>
string[] teamMembers = {"Matt", "Joanne", "Robert", "Nancy"};
foreach (var person in teamMembers)
{
<p>@person</p>
}
}
@{
<p>The number of names in the teamMembers array: @teamMembers.Length </p>
<p>Robert is now in position: @Array.IndexOf(teamMembers, "Robert")</p>
<p>The array item at position 2 (zero-based) is @teamMembers[2]</p>
<h3>Current order of team members in the list</h3>
foreach (var name in teamMembers){<p>@name</p>}
<h3>Reversed order of team members in the list</h3>
Array.Reverse(teamMembers);
foreach (var reversedItem in teamMembers){<p>@reversedItem</p>}
}
Team Members
Matt
Joanne
Robert
Nancy
The number of names in the teamMembers array: 4
Robert is now in position: 2
The array item at position 2 (zero-based) is Robert
Current order of team members in the list
Matt
Joanne
Robert
Nancy
Reversed order of team members in the list
Nancy
Robert
Joanne
Matt
Dictionary
@{var myScores = new Dictionary<string, int>();
myScores.Add("test1", 71);
myScores.Add("test2", 82);
myScores.Add("test3", 100);
myScores.Add("test4", 59);}
<p>My score on test 3 is: @myScores["test3"]%</p>
@(myScores["test4"] = 79)
<p>My corrected score on test 4 is: @myScores["test4"]%</p>
My score on test 3 is: 100%
79 My corrected score on test 4 is: 79%
Category: