/ / Jak zdefiniować zmienne na poziomie widoku w ASP.NET MVC? - asp.net-mvc, asp.net-mvc-3, html-helper

Jak zdefiniować zmienne na poziomie widoku w ASP.NET MVC? - asp.net-mvc, asp.net-mvc-3, pomocnik HTML

Mam częściowy widok cshtml (silnik Razor), żesłuży do renderowania czegoś rekurencyjnie. Mam dwie deklaratywne funkcje pomocnicze HTML zdefiniowane w tym widoku i muszę udostępnić między nimi zmienną. Innymi słowy, chcę zmienną na poziomie widoku (a nie zmienną na poziomie funkcji).

@using Backend.Models;
@* These variables should be shared among functions below *@
@{
List<Category> categories = new ThoughtResultsEntities().Categories.ToList();
int level = 1;
}

@RenderCategoriesDropDown()

@* This is the first declarative HTML helper *@
@helper RenderCategoriesDropDown()
{
List<Category> rootCategories = categories.Where(c => c.ParentId == null).ToList();
<select id="parentCategoryId" name="parentCategoryId">
@foreach (Category rootCategory in rootCategories)
{
<option value="@rootCategory.Id" class="level-@level">@rootCategory.Title</option>
@RenderChildCategories(rootCategory.Id);
}
</select>
}

@* This is the second declarative HTML helper *@
@helper RenderChildCategories(int parentCategoryId)
{
List<Category> childCategories = categories.Where(c => c.ParentId == parentCategoryId).ToList();
@foreach (Category childCategory in childCategories)
{
<option value="@childCategory.Id" class="level-@level">@childCategory.Title</option>
@RenderChildCategories(childCategory.Id);
}
}

Odpowiedzi:

6 dla odpowiedzi № 1

Nie możesz tego zrobić. Będziesz musiał przekazać je jako argumenty do swoich funkcji pomocniczych:

@using Backend.Models;
@{
List<Category> categories = new ThoughtResultsEntities().Categories.ToList();
int level = 1;
}

@RenderCategoriesDropDown(categories, level)

@helper RenderCategoriesDropDown(List<Category> categories, int level)
{
List<Category> rootCategories = categories.Where(c => c.ParentId == null).ToList();
<select id="parentCategoryId" name="parentCategoryId">
@foreach (Category rootCategory in rootCategories)
{
<option value="@rootCategory.Id" class="level-@level">@rootCategory.Title</option>
@RenderChildCategories(categories, level, rootCategory.Id);
}
</select>
}

@helper RenderChildCategories(List<Category> categories, int level, int parentCategoryId)
{
List<Category> childCategories = categories.Where(c => c.ParentId == parentCategoryId).ToList();
@foreach (Category childCategory in childCategories)
{
<option value="@childCategory.Id" class="level-@level">@childCategory.Title</option>
@RenderChildCategories(categories, level, childCategory.Id);
}
}

0 dla odpowiedzi nr 2

Możesz to zrobić. Widok to tylko klasa. Możesz łatwo zadeklarować nowe pole do tej klasy i używać go w dowolnym miejscu w kodzie widoku:

@functions
{
private int level = 0;
}