I am trying to add an item to the users Identity, but I think this could also be done another way.
I have added a few custom fields to the User Identity, but what I am trying to do is once the user has successfully logged in, I check if they are assigned to multiple branches(Store Locations) and then offer a list for the user to select which Branches they want data to be displayed for.
I have done this successfully, but now I want to store each of the branches in the users session/ cookie/ Identity (not sure what terminology to use). The user is displayed a number of checkboxes, and once they click save, I am unsure of what to do.
I need to save it in this function:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SelectBranch(params string[] branchNames)
{
foreach (var branch in branchNames)
{
//add branch to session/cookie/identity
}
return RedirectToAction("Index");
}
What steps do I need to take to be able to do this?
It depends on what you end goals are. Should the choice of branches be persistent or transient? Based on your comment, it sounds like you're wanting to save it for the current session, but then make the user choose again the next time they come back. If that's what you application truly needs, fine, but it seems to me that something like this should either be saved permanently, with the ability for the user to update those choices when they see fit, or completely temporary, i.e. for the current request, such as filtering a set of results by a branch or branches.
Storing for only the current browser session begs the question of whether the user will realize that their choices are being persisted across additional views, and conversely, whether they'll understand why they have to continually set branches each time they come back to the site.
That said, your choices:
ApplicationUser
and StoreBranch
(or whatever).Session
.Technically, you can use claims, but they aren't really a good fit for this. Claims should be used when either 1) the data being stored is not applicable to every user or 2) the data being stored is transient in nature, but should survive the session. A good example use of a claim would be storing an auth token from something like Facebook. Not every user will necessarily have a Facebook auth token, so it's not something you would want as a database column, and there's generally a lifetime for that auth token, making it temporary but still something you would need to hold on to even if the session was destroyed.
Based on your description of what you want to achieve, Session
is your best bet, but I would argue strongly that there's probably value in persisting this choice permanently, as long as the use can alter it later. To save it to the session, I would literally just save your string array directly to the session (no need for the for loop):
Session["BranchNames"] = branchNames;