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)) %>" />

2 Answers 2

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

Comments

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.

4 Comments

Even though it prints out, if you include inside <img>/src tag it's not picking the value. src= + <%= imgId %> +
@RameshTamma: What is @Url.Content and when does it get executed? Does it get executed on the server?
I am trying to resolve the URL using @Url.Content, it's Razor syntax and we can embed with in the client syntax.
@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.

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.