Frage

I used a function to construct an image path dynamically like this:

  function () {
            var name = $(this).attr('id') + '_o';
            var newsrc = '../../Content/HomePage/' + name + '.png';

And I want to assign the newsrc using Razor Url.Content to an image tag as its source. SO, I wish to do something like this:

  $(this).attr('src', '@Url.Content(newsrc)');

But VS show me red line saying that the newsrc is not exist within current context.. How can I use a variable along with Url.Content?

(Note: I am using this inside script tag...)

EDIT: An idea comes to my mind, perhaps the backdoor will be passing the newsrc to controller, use Url.Content there to resolve the url and pass it back? Is it feasible?

Any help will be appreciated..

War es hilfreich?

Lösung 3

Problem solved by my senior. I create an extra appsettings in web.config ( a WebDirectory) then assign the value as the folder path.

Then, at my code, I can easily construct my url using:

 System.Configuration.ConfigurationManager.AppSettings["WebDirectory"].ToString()...

Just share my solution here, hope it will help someone in future. Thanks.

Andere Tipps

When I am using this technique to send the path to JavaScript variable then it shows me -1 instead of path. The code is as below.

var path= <%= ConfigurationManager.AppSettings["FileManager"] %>;

You are attempting to directly pass a javascript variable to Asp.Net code - which is impossible.

You will have to remove the @Url.Content() and just use the relative path in your javascript:

$(this).attr('src', newsrc);

Or alternatively, use the Url.Content() to get the folder location, and append the filename in javascript, like this:

var name = $(this).attr('id') + '_o';
var newsrcFolder = '@Url.Content('../../Content/HomePage/')';
var newsrc = newsrcFolder + name + '.png';
$(this).attr('src', newsrc);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top