Home How to pass data from ASP.NET MVC view to javascript module?
Reply: 0

How to pass data from ASP.NET MVC view to javascript module?

Martin Shishkov
1#
Martin Shishkov Published in 2017-11-12 09:32:24Z

So, I am using webpack to bundle all my files required for a page, the output file is home.bundle.js:

The original file, home.jsx:

import React from "react";
import ReactDOM from "react-dom";
import {SomeComponent} from "../components/mobile/SomeComponent.jsx";

class Home {
    constructor(settings) {
        this.settings = settings;
    }

    start() {
        ReactDOM.render(<SomeComponent data={this.settings.someComponentData}/>,
            document.getElementById(this.settings.elementId));
    }
}

export {Home};

So I would like to be able to instantiate the Home class from an ASP.NET View and pass a settings object to it with data from the razor view model and call start(). However, I am getting an error message in the console:

Uncaught ReferenceError: Home is not defined

The view (super simplified):

@model SomeModel

<html>
    <head>
        ...
    </head>
    <body>
        <div id="someElement"></div>

        <script type="text/javascript" src="~/dist/mobile/home.bundle.js"></script>

        <script type="text/javascript">
            const homePage = new Home({
                someComponentData: @Model.SomeValue,
                elementId: "someElement"
            });

            homePage.start();
        </script>
    </body>
</html>

This was expected but I decided to try it anyway. Are there any best practices for doing this? Any ideas how to solve that? Thanks.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300018 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO