Razor 网页:如何创建可用于所有页面的变量? [英] Razor web pages: How do I create variable that is available to all pages?
问题描述
我有很多使用相同变量的页面.我想在一个页面中创建这些,这样我就不必一遍又一遍地输入它们.我该怎么做?
I have a lot of pages that is using the same variables. I would like to create these in a single page so I dont have to type them over and over again. How do I do this?
我尝试了 _appStart.cshtml 和 _PageStart.cshtml,但是当我运行我的内容页面时出现错误当前上下文中不存在名称 selectedData"
I tried both _appStart.cshtml and _PageStart.cshtml, but when i run my content page i get error "the name selectedData does not exist in the current context"
这是我的 _PageStart.cshtml:(也试过 _appstart.cshtml)
Here is my _PageStart.cshtml: (tried _appstart.cshtml too)
@{
var db = Database.Open("razortest");
var selectQueryString = "SELECT * FROM tbl_stasjon ORDER BY nr";
var selectedData = db.Query(selectQueryString);
}
我所有的页面都包含这个:
And all of my pages includes this:
@foreach(var row in (selectedData)) {
html here...
}
推荐答案
对于一个相当直接的解决方案,您可以在 App_Code
中创建一个静态类/方法,返回您的查询对象,然后调用它任何需要的方法:
For a fairly straight-forward solution you could create a static class/method within App_Code
that returns your query object and then call that method wherever you need it:
using System;
using System.Collections.Generic;
using System.Web;
using WebMatrix.Data;
public static class MyClass
{
public static IEnumerable<dynamic> GetData()
{
var db = Database.Open("razortest");
var selectQueryString = "SELECT * FROM tbl_stasjon ORDER BY nr";
return db.Query(selectQueryString);
}
}
然后在你的脚本中你可以:
Then in your scripts you can do:
@foreach(var row in MyClass.GetData()) {
html here...
}
可能会有更优雅、更高效的方法来实现这一点,但它们取决于您究竟在做什么.出于遵循教程的目的,这应该符合您的目的.
There will likely be more elegant and performant ways to achieve this but they depend on what exactly you're doing. For the purposes of following a tutorial this should serve your purposes.
这篇关于Razor 网页:如何创建可用于所有页面的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!