1

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!

6
  • 2
    You could declare a variable in javascript at the top of your View and serialize the Model into this variable, if this runs before you import your javascript file, it will be available as a variable in the javascript file. Commented Jul 22, 2022 at 14:38
  • Have you tried to use an ajax call? Commented Jul 22, 2022 at 14:40
  • @Bjop No, I haven't. I'm pretty sure it would work, but to me @ Model seems like it was thought for this exact purpose, so I'm a bit hesitant to do it with ajax. I just want to know what the best approach to this would be, and whether or not it's possible to do it with @ Model. I updated my question because I didn't really say this. Commented Jul 22, 2022 at 14:46
  • @MarcMiller in school we always had to do it with ajax. To my knowlidge it is possible to do with @ model but your script needs to be in the same file as the html code. Commented Jul 22, 2022 at 14:50
  • 1
    @RyanWilson I tried this out just with an int and it worked perfectly, this also allows me to do it using @ Model which is what feels like "the right way" to do it to me. I'm still unsure what would be the best approach to this, but your answer is exactly what I was looking for. Commented Jul 22, 2022 at 14:55

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for this answer, this is exactly what I was trying to do
@MarcMiller You may want to view my update as this sets the javascript variable to an object instead of string so you don't have to deserialize it.
Sadly the SerializeObject did not work for me as I have Vector3's in my Object, but I found a workaround.
1

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.

1 Comment

Thanks a lot for this great answer, helps me get some insight on how this could be handled. When googling for answer, I actually found both the cookie and HTML ways to do it, but cookies seemed overkill for something as trivial as passing data and HTML injection seemed like a bigger hack then creating a javascript variable in the .cshtml and accessing that in my script.js. Thank you also for explaining why injection into the .js file is not possible, that makes a lot more sense now! This is exactly the answer I was looking for, but I accepted Ryan's answer since that gives a specific solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.