gpt4 book ai didi

asp.net-mvc - 如何在ASP.NET MVC中定义 View 级变量?

转载 作者:行者123 更新时间:2023-12-04 18:14:25 25 4
gpt4 key购买 nike

我有一个cshtml部分 View (Razor引擎),用于递归渲染某些内容。我在此 View 中定义了两个声明性HTML帮助器函数,我需要在它们之间共享一个变量。换句话说,我想要一个 View 级变量(而不是功能级变量)。

@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);
}
}

最佳答案

你做不到您将需要将它们作为参数传递给您的辅助函数:

@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);
}
}

关于asp.net-mvc - 如何在ASP.NET MVC中定义 View 级变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6534020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com