Razor web pages: How do I create variable that is available to all pages?

人走茶凉 提交于 2020-01-05 08:03:43

问题


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?

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"

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...    

}

回答1:


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.




回答2:


You could get use of the session and try to use a controller.

See

  • Adding a Controller
  • Adding a View
  • Adding a Model

Override OnActionExecuting within your controller (wihtin the constructor the Session is not available)

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    base.OnActionExecuting(filterContext);
    if (Session != null)
        Session["selectedData"] = "Hello World";
}

And within the Action

Public ActionResult View1(){
     return View(Session["selectedData"];
}

Within your view you can handle this data

@{
ViewBag.Title = Model;
}

That's a simple solution with a string. You can create strongly typed views and get a very comfotable way to handle this data within your views.



来源:https://stackoverflow.com/questions/21246087/razor-web-pages-how-do-i-create-variable-that-is-available-to-all-pages

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!