srinath madusanka
srinath madusanka

Reputation: 25

pass Global.asax.cs file variable in application start method to my controller asp.net mvc4

i created variable in application start method Global.asax.cs file. i want to pass this variable into my controller.i am new to asp.net. i am using asp.net mvc4 Razor here is my code global aspx.cs file

AreaRegistration.RegisterAllAreas();
            const string Chars = "ABCDEFGHIJKLMNPOQRSTUVWXYZ0123456789";
            var random = new Random();
            var result = new string(
                Enumerable.Repeat(Chars, 12)
                    .Select(s => s[random.Next(s.Length)])
                    .ToArray());

            var path = Server.MapPath("~/Content/" + result);

                     Directory.CreateDirectory(path);

i want to get this path variable to my controller how i accomplish this

Upvotes: 1

Views: 2737

Answers (2)

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

You can't access variables declared in global.asax file.

Instead of using variable "path" just do like this :

Global.asax :-

AreaRegistration.RegisterAllAreas();
        const string Chars = "ABCDEFGHIJKLMNPOQRSTUVWXYZ0123456789";
        var random = new Random();
        var result = new string(
            Enumerable.Repeat(Chars, 12)
                .Select(s => s[random.Next(s.Length)])
                .ToArray());

        Application["Path"] = Server.MapPath("~/Content/" + result);  <--------

        Directory.CreateDirectory(Convert.ToString(Application["Path"]));

Controller :-

public ActionResult Index()
{
  var path1 = Convert.ToString(HttpContext.Application["Path"]));  <--------
  return RedirectToAction("About");
}

Now Application["Path"] can be used anywhere in your entire application.

Upvotes: 1

malkam
malkam

Reputation: 2355

Try this

  1. Use Application variable as stated above.

            or
    
  2. Declare static variable in Global.asax and access it in controller

    public class MvcApplication:System.Web.HttpApplication

      {
    
          public static string path;
    
       protected void Application_Start()
            {
           AreaRegistration.RegisterAllAreas();
         const string Chars = "ABCDEFGHIJKLMNPOQRSTUVWXYZ0123456789";
          var random = new Random();
          var result = new string(
            Enumerable.Repeat(Chars, 12)
                .Select(s => s[random.Next(s.Length)])
                .ToArray());
    
        path = Server.MapPath("~/Content/" + result);
       Directory.CreateDirectory(path);
            }
       }
    

    In your controller

    var path=MvcApplication.path

Upvotes: 0

Related Questions