-4

I have 2 declared static dictionaries in Home Controller:

private static Dictionary<string, string> _existingBranchesDict;
private static Dictionary<Guid, string> _choosedBranches;

I declared them as static because they're used in many methods of the same Controller and to prevent null reference exception. The problem is they should be unique for per-user but because of static modifier these dictionaries are shared between all users. Where I have to store these data and don't have any null reference exception when I use them in different methods? I use them in different methods such as:

[HttpPost]
    public void DeleteBranch(Guid partialViewID, int deletedBranchIndex)
    {
        if (_choosedBranches.ContainsKey(partialViewID))
        {
            var resettedBranch = _choosedBranches[partialViewID];
             _existingBranchesDict[resettedBranch] = "Enabled";
            _choosedBranches.Remove(partialViewID);
        }
    }

[HttpPost]
    public void LoadBranch(string Name, Guid ID)
    {
        _existingBranchesDict[Name] = "Disabled";

        if (_choosedBranches.ContainsKey(ID))
        {
            _existingBranchesDict[_choosedBranches[ID]] = "Enabled";
        }
        _choosedBranches[ID] = Name;
    }

Which are called by AJAX from different partial views rendered on a single view. They are storing same data for all drop down lists for each partial view and when User choose a single element, it should be removed from other drop down lists of other partial views.

David
  • 19
  • 7
  • 4
    If they should be unique per request, why are you marking them as `static`? Each action should represent a unique request, so your design does not make a lot of sense. Please [edit] your question and clarify what you are actually trying to accomplish – Camilo Terevinto Jul 16 '18 at 14:36
  • It sounds like you might want to look into Dependency Injection https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1 – p3tch Jul 16 '18 at 14:40

1 Answers1

0

You simply need to use HttpContext.Items property:

Gets or sets a key/value collection that can be used to share data within the scope of this request.

Set
  • 47,577
  • 22
  • 132
  • 150