Sohrab
Sohrab

Reputation: 11

How to access a model property from seperate javascript file? (MVC)

Right now I am using a model property in the javascript as one of the values in a json object that i pass to the controller. The problem is that the javascript will be seperated in a .js file and will not be able to access @Model. So the question is; how do i access model from a seperated .js file?

Upvotes: 1

Views: 1117

Answers (2)

invernomuto
invernomuto

Reputation: 10211

You could try RazorJs (unfortunatelly seems no more mantained)

Write Razor-Style C# or VB.NET inside your Javascript Files. Also contains an http handler for serving, when needed, those files.

You could do something like this:


Views/Home

@{
    ViewBag.Title = "Home Page";
}

@Html.RazorJSInclude("~/Scripts/App/TestRazorJS.js")
<button id="btnSearch" name="submit" type="button" onclick="LoadFromRazor()">Search</button>

Scripts / App / TestRazorJS.js

function LoadFromRazor() {
    $.ajax({
        url: '@Url.Action("Test", "Home")',
        datatype: 'json',
        type: 'GET',
        cache: false,
        success: function () { console.log('done'); },
        error: function (xhr, status, error) {
          console.log(status);

        }
      });
    }

Upvotes: 1

Hypnobrew
Hypnobrew

Reputation: 1140

You can load the external javascript as usual and the send the model value as a property to an init method like this in your view:

<script type="text/url" src="externalscript.js"/>
<script type="text/javascript">
        $(function() {
            var model = home.views();
            model.init({
                modelProperty: '@Model.Property',
            });
</script>

And then your externalscript.js looks like:

(function (window) {
    home = window.home || {};
    home.views = function () {
        pub.init = function (options) {
            var property = options.modelProperty;
        };
        return pub;
})(window);

And you can use your property like you want to in the external script.

Upvotes: 1

Related Questions