简体   繁体   中英

ASP.NET MVC 2 & Dynamic JavaScript

I have an unordered list that when an item is clicked it displays several images using the Fancybox JavaScript plugin.

I am trying to convert this to ASP.NET MVC 2 and I want to dynamically pass the Image Paths and Title etc. to the JavaScript so that they are not hard coded.

HTML

  <ul>
    <li><a href="DisplayImages();" title="Images"> Show Images</a></li>
    </ul>

Javascript

function DisplayImages() {

    $.fancybox([
{ 'href': 'Image Path goes here', 'title': 'Image Title goes here' },
{ 'href': 'Another Image path goes here', 'title': 'Another image title' }
], {
    'padding': 0,
    'transitionIn': 'none',
    'transitionOut': 'none',
    'type': 'image',
    'changeFade': 0

})
};

Is this possible to do? Any help is much appreciated

Thanks

If i understood You correctly, You might be looking for this:

function DisplayImages() {
  $.fancybox([
    { 'href': '<%= Model.ImagePath %>', 
      'title': '<%= Model.ImageTitle %>' },
    { 'href': '<%= Model.AnotherImagePath %>', 
      'title': '<%= Model.AnotherImageTitle %>' }], 
    {'padding': 0 //yada yada}    
   })
};

Assuming You are writing this code in aspx/ascx view, it will embed data from server side directly to rendered html similarly like ' echo ' does in PHP.

Model is an object that You will pass to view from controller.

Here's how-to by Stephen Walther.


If Your problem actually isn't that much about embedding data from server side but passing multiple image paths and titles to plugin as an argument, You might want to check out how JSON serialization (<--that's only one way to accomplish that) works. I most likely would create htmlHelper that serializes passed object and use it like this:

$.fancybox([<%= Html.ToJSON(Model.Images)%>], 
  {'padding': 0 //yada yada}    
})

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