0

I am unable to prepare string url for @Url.Content method.

Here is my block of code from Underscore template

 <%  var imgId = "~/Content/images/" +pocket.get('imageId'); %>   
        <div class="image1">       
            <% alert(imgId); %>         
            <img src= "@Url.Content("+<% imgId %>+")"  alt="Assigned Details" />

I'll pass the "imageId" through pocket object.

I tried using following approach as well. Getting compilation error for imgId variable

<img src= "<%= @Url.Content(string.Format("~/Content/Images/{0}", imgId)) %>" />

Ramesh Tamma
  • 13
  • 1
  • 6

2 Answers2

0

You use <% ... %> to evaluate some JavaScript in an Underscore template but you use <%= ... %> if you want the output to end up in the result; from the fine manual:

Template functions can both interpolate variables, using <%= … %>, as well as execute arbitrary JavaScript code, with <% … %>.

You're looking to interpolate the imgId value into the result so you want this:

<img src= "@Url.Content("+<%= imgId %>+")"  alt="Assigned Details" />

Simplified Demo: http://jsfiddle.net/ambiguous/9gyKC/

Presumably @Url.Content is something that gets run on the server to produce a src attribute for a given resource. If that's the case then you'll have to rethink how this works; the <%= ... %> stuff happens in the browser after @Url.Content has been executed so it will be too late when the Underscore template runs. Your note about an imgId error with this:

<img src= "<%= @Url.Content(string.Format("~/Content/Images/{0}", imgId)) %>" />

supports this theory. Your server code doesn't know what imgId is, only the client-side JavaScript does.

user3335966
  • 2,673
  • 4
  • 30
  • 33
mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Even though it prints out, if you include inside /src tag it's not picking the value. src= + <%= imgId %> + – Ramesh Tamma May 08 '12 at 02:44
  • @RameshTamma: What is `@Url.Content` and when does it get executed? Does it get executed on the server? – mu is too short May 08 '12 at 03:22
  • I am trying to resolve the URL using @Url.Content, it's Razor syntax and we can embed with in the client syntax. – Ramesh Tamma May 08 '12 at 12:01
  • @RameshTamma: But `@Url.Content` and `<%= imgId %>` are being evaluated in different places at different times so you can't mix them like that. The Razor stuff is evaluated before Underscore gets to the template. – mu is too short May 08 '12 at 16:05
0

Solution: Finally I figured out the solution from another thread: Call js function from underscore template 1. js function

<script type="text/javascript">
var fullPath = '@HttpContext.Current.Request.Url.Scheme://@HttpContext.Current.Request.Url.Authority';
function GetPath(url) {
    return fullPath + url;
}

  1. call js from your code: <img src= '<%= GetPath(imgId) %>' alt="Med Assigned" />
Community
  • 1
  • 1
Ramesh Tamma
  • 13
  • 1
  • 6