0

In a ASP.NET Web Pages 'site', created with webmatrix (razor template, c# code).

Can I set a variable in the cshtml template that would be 'global' (AppState) WITHOUT executing that page?

I know that I can set "AppState.Whatever = " on the page, but I have to 'visit' the page, so that the code 'runs'.

Can I set "Something.Whatever = " inside te cshtml template, without visiting the template. This would only be possible if these pages are 'compiled' or interpreted when they are saved. Is such a thing possible?

Thanks!

Tixiv
  • 170
  • 1
  • 7
  • I'm not sure what the purpose of doing this is. Why do you need to have a variable set when the page hasn't been visited? – NotMe May 13 '13 at 20:27
  • http://www.asp.net/web-pages/tutorials/working-with-pages/18-customizing-site-wide-behavior – SLaks May 13 '13 at 20:27

2 Answers2

1

You can add a file named _AppStart.cshtml to the root of your site. It will execute when the first request is made to your application. You can set global variables in that.

Look for the section titled Application Variables in my article here: http://www.mikesdotnetting.com/Article/192/Transferring-Data-Between-ASP.NET-Web-Pages

Mike Brind
  • 28,238
  • 6
  • 56
  • 88
  • The use case is the following: when I add a new page (cshtml) to my site. I would like to add this page automatically to my 'menu', without editing any other page then the new cshtml page. Just add a page, and it shows up in the menu without being 'executed'. So how to do this without editing _Appstart.chtml? – Tixiv May 14 '13 at 06:36
  • I would never have guessed in a million years from your question what you are trying to do. You can write some code that lists the files in your site and generates a menu from the result. If you add a page, it will automatically get picked up by the code. – Mike Brind May 14 '13 at 08:44
  • So there is NO POSSIBLE WAY this could work? Besides Directory.GetFiles? – Tixiv May 14 '13 at 09:16
  • 1
    There is no way you can do this that I can think of that doesn't rely on some kind of file watcher - unless your menu is database-driven, in which case you can of course update the database with details of the newly added file. – Mike Brind May 14 '13 at 12:17
1

You can not set your variable as global to _AppStart.cshtml. It will not compile variable to all the pages. You can try to add following to _AppStart.cshtml, but it can only add or compile integers to all pages of your cshtml site.

App.MyInt = 0;

However you can add file named Global.cs to App_Code folder

using System;
using System.Collections.Generic;
using System.Web;

/// <summary>
/// This class specifies global variables
/// </summary>
public static class Global
{
    public const string StringName = "Some String";
    public const int IntName = 100;
    // Or anything else you want to add
}
Apurva
  • 148
  • 1
  • 14