如何在 ASP.NET MVC 中定义视图级变量?
我有一个 cshtml 部分视图(Razor 引擎),用于递归渲染某些内容。我在此视图中定义了两个声明性 HTML 帮助器函数,我需要在它们之间共享一个变量。换句话说,我想要一个视图级变量(而不是函数级变量)。
@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);
}
}
I have a cshtml partial view (Razor engine) that is used to render something recursively. I have two declarative HTML helper functions defined in this view and I need to share a variable between them. In other words, I want a view-level variable (not function-level variable).
@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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能这样做。您需要将它们作为参数传递给辅助函数:
You can't do this. You will need to pass them as arguments to your helper functions:
你可以这样做。 View只是一个类。您可以轻松地在此类上声明一个新字段,并在视图代码中的任何位置使用它:
You can do this. View is just a class. You can easily declare a new field onto this class and use it anywhere in the code of your view: