简体   繁体   中英

How to pass model data from partial view to JavaScript?

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?
})

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... 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM