简体   繁体   中英

Using asp.net <%: %> syntax to generate javascript in an MVC application

I have a for loop to loop through my list of SliderItems which contain an ID, ImageUrl, and a link Url.

<% foreach (var item in Model) { %>
    <a href="#"><img id="<%: item.ImageID %>" src="<%: item.ImageUrl %>" class="slide" alt="" /></a>
<%} %>

I need to loop through and generate the data parameters for this javascript automatically in a similar fasion, replacing the "slide-img-#" with my SliderItem.ID

 <script type="text/javascript">
           if (!window.slider) var slider = {}; slider.data = [{ "id": "slide-img-1" }, { "id": "slide-img-2" }, { "id": "slide-img-3" }, { "id": "slide-img-4"}];
       </script>

Whats the best way to go about this?

Personally I like to generate all json data with its own view and do an async call over or you can do this

 <script type="text/javascript">
  <%=Html.Action("thingie").ToString() %>
  </script>

with the controller

public ActionResult thingie()
    {
        var retVal = Json(new { blah = 1, foo = 2, bar = 3 }, JsonRequestBehavior.AllowGet);
        retVal.ContentType = "text/html";
        return retVal;
    }

or the simplest answer is to do exactly what you do above

 <script type="text/javascript">
       if (!window.slider) var slider = {};
        slider.data = [
           <% foreach (var item in Model) { %>
                 { "id": "slide-img-1" },
            <%} %>
            ];
   </script>

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