I have an ASP.Net Core application. I have a Class with some attributes:
public class myClass
{
public string name {get; set;}
public int id{get; set;}
...
}
and in PageModel of Index.cshtml, I am creating on object of that class and setting it is a property:
public class IndexModel : PageModel
{
public myObj data { get; set; }
public void OnGet(int inputId)
{
data = new myClass();
data.name = "name";
data.id = inputId;
}
}
Now, in my Index.cshtml, I have some default html and then I add a script like this:
<script type="module" src="~/built/script.js"></script>
Finally, my question: I need the data that I have defined in IndexModel in my script.js. In a normal cshtml-page, I would do @Model.data, but that decorator is not available in my js file. Is there a way to do this, or should I use one of the following which I think might work:
- Adding an API-controller in ASP.Net and calling it in my script.js with ajax: I think this should work, but it seems to me like I am supposed to do it with @Model instead
- Somehow storing it in a global variable in my .cshtml file and then accessing that global variable in script.js: Seems like a hack
I'm pretty new to ASP.Net and JS, so there might be an obvious answer to this that I'm just too inexperienced to know. Any help is appreciated!