Skip to content
Advertisement

Passing Object from ASP.Net to javascript

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!

Advertisement

Answer

You could use model binding as intended and convert the model to a javascript variable at the top of your view, then it will be available in the script file as a javascript variable as long as you load the javascript file after you create the variable to hold your model.

—YOUR VIEW—

@model YourModel
@using Newtonsoft.Json;
<script type="text/javascript">
    let mymodel = @Html.Raw(JsonConvert.SerializeObject(Model));
</script>

–Import your script file after creating javascript variable and mymodel should then be available

<script type="text/javascript" src=""></script>

–Use mymodel in your script file

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement