问题
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