0

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?

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.