将值从c#传递到cshtml到TypeScript

问题描述:

我有一个项目,其中我通过类似以下方式将数据从C#传递到cshtml:

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();
    }

然后在cshtml文件中接收到该值,我可以将其读取为

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

var temp = ViewData["temp"];

我有一个打字稿文件,然后从此cshtml文件启动.我的问题是,如何在打字稿代码中使用此temp变量.我不想为此临时数据创建一个'div'元素,然后在打字稿中读取其值,因为从安全角度来看这不是一件容易的事.

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?

在由 Index 操作返回的视图中,只需选择一个现有元素(您可以选择 body 元素(如果您的视图包含它),然后在该元素中添加一个 data-* 属性(您可以将其命名为 data-temp ),如下所示:

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>

在您的Typescript文件中,我想您正在使用jQuery,因此获取数据值如下:

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

let dataTemp = $("SomeElementInMyView").data("temp");