5

I have been using something like this inside Razor

@section Includes {  
      <script type="text/javascript">
        var somestuffneeded = @(Html.Raw(Json.Encode(Model.datamember))); 


      </script>

}

But this looks not so clean because it goes in the same file as the layout, (since it won't work from the .js file directly). Any clean alternatives to accessing and viewing the ViewModel passed inside .js file?

2
  • 1
    For simple pages, I've found what you have above works pretty well. For more complex situations, using a WebAPI controller might be the better way to go. Commented May 14, 2014 at 21:43
  • I knew this and forgot. I keep forgetting things. It must be there in my old questions here on stack overflow. Commented May 14, 2014 at 22:05

1 Answer 1

1

You can't directly access ViewModel in .js file because its static file on your web server. But there is a workaround that you can pass ViewModel to .js file with parameter.

some .js File

function Common() {
    var _this = this;

    this.viewModel = null;

    this.showViewModel = function () {
       alert(_this.viewModel);
    };
}

var common = null;
$().ready(function () {
    common = new Common();
});

then just pass ViewModel when View is Loaded

@section Includes {  
  <script type="text/javascript">
    var somestuffneeded = @(Html.Raw(Json.Encode(Model.datamember))); 
    $(document).ready(function () {
          common.viewModel = somestuffneeded;
          common.showViewModel();
    });
  </script>
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think he's asking for something else. He's saying, how may I avoid that var somestuffneeded = @... statement. I know you answered it with a "you can't".

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.