jimbo-ish
jimbo-ish

Reputation: 105

Passing data to a taghelper

I'm using a TagHelper to localise any text on a number of CSHTML pages. In order to select the correct translation the TagHelper needs to know the locale that the user currently has selected, which is held in the user's LocalStorage.

I have been able to populate a ViewBag with this value, so I can add it somewhere on the page using Razor syntax but I can't figure out how to make this information available every time a TagHelper processes a specified HtmlTargetElement. I've a feeling that the answer is somewhere in TagHelperContext and have tried adding the locale to the page's <body> tag but the order that the HtmlTargetElements are processed do not seem to be fixed.

Upvotes: 0

Views: 622

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239380

which is held in the user's LocalStorage

Local storage is not accessible server-side (where the tag helper is being rendered). Therefore, there is no way to achieve this. You could perhaps use the session, instead, which you could then access in your tag helper via ViewContext. In your tag helper add the following property:

[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }

Then, you can access the session via ViewContext.HttpContext.Session.

Upvotes: 2

Related Questions