Webmatrix 2: Storing static values

删除回忆录丶 提交于 2020-01-11 09:26:06

问题


Where would be the best place to store static values. And how would I access it.

I want to be able to access static values from any page. But only have to define them in one place.

For example 'email' and 'phoneNumber'

I have tried things like Session and PageData, and defining the variables in my header (used by all pages) but this does not work.

The partial is initialised after the page, so it either doesnt work at all, or doesnt work on first time load.

E.g. First time Load:

Page Loaded <- Tries to Access variable. Not initialised.

Header Partial Loaded <- Variable initalised.

Result. Page does not show variable.

I have considered storing it in the config file. But I have no idea how to access this from Webmatrix 2. I could just create a txt/ini file or something but surely parsing a file isn't the best way to do it. - I have since tried this and it doesnt seem valid like in mvc3 (config),and txt files are not practical to read for each request.


回答1:


By "static", if you mean values that don't change across the lifetime of the application, you would normally use HelperPage.App property for storage. It is based on the dynamic type so you can create arbitrary properties:

App.Email = "someone@somewhere.com"; 

Or you can use the more traditional name/value collection approach with AppState:

AppState["email"] = "someone@somewhere.com";

However, if your "static" variables are user-specific, you should use Session as that is scoped to the user. Or use a database if you want to store them permanently.

You can set session values in _PageStart.cshtml (may need creating), or in the Session_Start event of the global.asax file and then access them in any partial / view you desire.



来源:https://stackoverflow.com/questions/12263892/webmatrix-2-storing-static-values

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