Use a variable that store image path in Razor Url.

2019-08-27 16:00发布

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..

3条回答
2楼-- · 2019-08-27 16:42

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);
查看更多
劳资没心,怎么记你
3楼-- · 2019-08-27 16:46

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.

查看更多
贪生不怕死
4楼-- · 2019-08-27 16:54

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"] %>;
查看更多
登录 后发表回答