Home > database >  Passing Object from ASP.Net to javascript
Passing Object from ASP.Net to javascript

Time:07-23

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!

CodePudding user response:

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 = @HtmlRaw(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

CodePudding user response:

There are four ways to do this, you found two of them. I'll give you the pro's and cons in order of complexity:

AJAX:

It's not that hard, use the "fetch" method built into the window object. But, it's asynchronous so you have to deal with callbacks in JavaScript, you will need to secure the API so it only accepts authorized clients (usually done with OAuth, but you could just inject an authorization code for the client JavaScript to use), and you need to identify yourself (like a session) to the API to get the right data so that is another code. Oh wait, we have to inject a code? So what's the point of using AJAX? True, only use AJAX when you need to dynamically get new data without reloading the page!

JavaScript injection:

You never want to inject into a .js file, they should be static and that's why you discovered it won't work. So you have to inject some JavaScript code creating variables into the page that is loading the JavaScript. That's what you proposed and that is completely fair to do. It's isn't a hack. It should be one variable with a JSON string.

Cookie:

Put the data into a temporary cookie delivered with the page and read the cookie from JavaScript. This is cleaner than the variable solution, but isn't the simplest way.

HTML injection:

There is one other possibility for using @Model, instead of injecting the JSON string into a JavaScript variable, which requires injecting JavaScript tags too, put it into a property on an HTML element and then access the property from JavaScript. This is simpler and my preferred method. Property names beginning with "data-" are designed for this.

  • Related