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?

sarsnake
  • 26,667
  • 58
  • 180
  • 286
  • 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. – Nate May 14 '14 at 21:43
  • I knew this and forgot. I keep forgetting things. It must be there in my old questions here on stack overflow. – Water Cooler v2 May 14 '14 at 22:05

1 Answers1

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>
}
Mike
  • 3,766
  • 3
  • 18
  • 32
  • 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". – Water Cooler v2 May 14 '14 at 22:06