簡體   English   中英

如何從另一個類 C#/MVC 訪問屬性

[英]How to Access to a property from another class C#/MVC

基本上問題是我需要訪問類中的當前用戶身份。 我在 MVC 控制器中得到它很好,但我需要能夠在類中訪問。 所以我試圖使用屬性來設置它,但無法弄清楚 get 部分。 這是代碼:

//Employee.cs  
public class CurrUser
    {
        public string USERID{ get; set; }

    }

MVC控制器:

//HomeController
        public async Task<JsonResult> GetDefaultMgrGeid()
        {
            string Soeid = User.Identity.Name.Split("\\".ToCharArray())[1];
            //setting prop here
            CurrUser emp = new CurrUser();
            emp.USERID = Userid;

            var task = Task.Run(() => DAL.Employee.GetDefaultMgr(Soeid));

            var retData = await task;
            return new JsonResult
            {
                ContentType = "application/json",
                Data = retData,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                MaxJsonLength = int.MaxValue
            };
        }

我需要訪問(獲取)此處的值:

public class HR
    {
    // I tried this but did not work either
        // public CurrUser user{ get; set; }
        //  public string GetUser
        //  {
        //      get
        //     {
        //          return user.USERID;
        //     }
        //  }
       public static IEnumerable<DTO.Employee> GetGlobalMgrs()
        {
         string mrgID = CurrUser.??;// I can't access it here
        }

}

請指導!

改成這樣:

    public class HR
    {
       //by setting this property to static your static methods in this class can access it
       public static CurrUser user{ get; set; }

       public static IEnumerable<DTO.Employee> GetGlobalMgrs()
       {
         string mrgID = user.USERID;
         //put your other code here like retrieving the list
       }
    }

如果您需要從其他類訪問它:

這樣做: Hr.user確保您using正確的命名空間

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM