3

I have a project where I am passing the data from C# to cshtml by something like this:

public IActionResult Index()
    {
        ViewData["temp"] = "abc"
        return View();
    }

This value is then received in the cshtml file where I can read this as

var temp = ViewData["temp"];

I have a typescript file that is then booted from this cshtml file. My question is, how can I use this temp variable in my typescript code. I don't want to create a 'div' element for this temp data and then read its value in typescript as this will not be a clean thing to do from security perspective.

Can you please suggest some way to do it in a proper way?

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
RichaS
  • 219
  • 3
  • 14

2 Answers2

4

In your view returned by the Index action just choose an existing element (you can choose the body element if your view contain it) and in that element add an data-* attribute (you can name it data-temp) like below :

<SomeElementInMyView data-temp="@temp">...</SomeElementInMyView>

In your Typescript file, I suppose you're using jQuery so get the data value like this:

let dataTemp = $("SomeElementInMyView").data("temp");
CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
  • 1
    Even if I do this, the data-temp value is visible in the page's DOM tree. Is there some way we can hide it from the DOM tree? – RichaS Apr 25 '18 at 07:47
  • 1
    No. If you need your data from Razor Page to be accessible into your typescript/javascript file you must put it into the DOM file. Typescript/javascript file then inspect the DOM and get the data. This is the good practice. – CodeNotFound Apr 25 '18 at 07:49
0

You can pass it as string variable in html eg.

let typeScriptVariable: string = "@temp";
Lit
  • 116
  • 5