1

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?

2
  • 1
    A workaround is to create javascript variable in your view and access in js file: <script> var varWithValue = '@Model.Value'; </script> And access the varWithValue in your js file. Commented Apr 4, 2016 at 19:30
  • @GeneR It was on my suggestion the user asked, so I feel partly responsible. Is there an alternative way to access the page's model? Or is the @Model.Blopp the only choice? Commented Apr 4, 2016 at 19:31

2 Answers 2

1

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.

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

Comments

1

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);

        }
      });
    }

Comments

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.