2

I have a strongly typed with A model Partial view.

Is it possible to pass the model data to an external JavaScript?

My partial view temporary is like this:

@model MyProject.Models.myModel
<script src=".../myScript.js"><script>
<span>
      @Html.DisplayFor(model => model)
      //how do I pass data to myScript.js?
</span>

In external JavaScript (myScript.js):

$(document).ready(function () {
    //how do I get data from the partial view?
})
pnuts
  • 58,317
  • 11
  • 87
  • 139
Skeiths Chew
  • 151
  • 1
  • 13

1 Answers1

0

First of all, having scripts inside partial views is not recommended, so I'll illustrate my answer using a non-partial view.

What you are asking is not possible, however you could certainly have something like this in your Partial View's Parent view:

@model MyProject.Models.ParentModel
...
<script src=".../myScript.js"><script>
...
<span>
      ...
      @Html.DisplayFor(model => model)
      ...
</span>
...
<script>
        $(document).ready(function(){
           var jsVariable = '@Model.MyModelVariable'
        })
<script>  
...

That way you'll get in your script the benefits of a strongly typed model, although note that this violates the unobtrusive js principles... However, making a rational use is harmless.

I find a good practice to use the Module pattern like this:

<script>
   $(document).ready(function(){
       var mod = new MyModule({
             foo : '@Model.Foo',
             bazSelector: '@Html.NameFor(model => model.Baz).ToString()'
             // ... other module options
       })
   });
<script>

Then in your external file you can have your module:

function MyModule(options){
  // use the options created from a strongly typed model... 
}
Community
  • 1
  • 1
Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
  • I think I will go for ajax calling on javascript to get all the data from the controller instead of doing it seperately. Thanks for your advice :) – Skeiths Chew Oct 17 '14 at 06:42