2011-06-30 26 views
5

私は再帰的に何かをレンダリングするために使用されるcshtmlパーシャルビュー(Razorエンジン)を持っています。私はこのビューで定義された2つの宣言的なHTMLヘルパー関数を持っており、それらの間で変数を共有する必要があります。つまり、ビューレベルの変数(関数レベルの変数ではない)が必要です。ASP.NET MVCでビューレベルの変数を定義する方法は?

@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='[email protected]'>@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='[email protected]'>@childCategory.Title</option> 
     @RenderChildCategories(childCategory.Id); 
    } 
} 

答えて

6

これはできません。

@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='[email protected]'>@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='[email protected]'>@childCategory.Title</option> 
     @RenderChildCategories(categories, level, childCategory.Id); 
    } 
} 
+0

本当ですか?変数を共有できないのは本当にばかげているということです。私は、かみそりのビューをスコープと考えています。このスコープで変数を定義できると思います。この答えは私がやりたいことをするのに役立ちましたが、私はそれについては分かりません。とにかく助けてくれてありがとう。 :) –

0

これは、ヘルパー関数の引数として渡す必要があります。ビューは単なるクラスです。このクラスに新しいフィールドを簡単に宣言して、ビューのコードのどこにでも簡単に使用できます。

@functions 
{ 
    private int level = 0; 
} 
+0

完了。コメントを削除しました。 –

関連する問題