简体   繁体   English

具有Url.Content的javascript路径

[英]javascript path with Url.Content

I am trying to get standard path with javascript for images in my project I used src for image as below 我试图在我的项目中使用javascript获取图像的标准路径,我将src用于图像如下

document.testImg.src = '../Images/test.png';

Do we have any option like below to make path consistent? 我们是否可以像下面这样使路径保持一致?

document.testImg.src = '@Url.Content(~/Images/test.png)';


<img name="testImg">

Thanks in advance 提前致谢

As you probably know you can't use Razor in Javascript unless that script is part of the Razor view. 您可能知道,除非该脚本是Razor视图的一部分,否则无法在Javascript中使用Razor。 It's not the "sexiest" way but one way out is to have a "global" javascript URL variable in your Layout View/MasterPage. 这不是“最简单”的方法,但是一种解决方法是在布局视图/母版页中具有“全局” javascript URL变量。

for example in your shared layout you'll have a variable: 例如,在共享布局中,您将有一个变量:

var AppUrl = '../Content/Images/';

so then in all your views you can use this consistent variable: 因此,在所有视图中,您都可以使用以下一致变量:

var myImageUrl = AppUrl + 'image.jpg';

ps Don't want to use variables ? ps不想使用变量? Stick a function in your shared view instead: 将功能粘贴在共享视图中:

For example in your shared layout you'll have a function: 例如,在共享布局中,您将具有以下功能:

function AppURL(url)
{
 return '../Content/Images/' + url;
}

so then in all your views you can use this: 因此,在所有视图中,您都可以使用以下命令:

var myImageUrl = AppUrl('image.jpg');

I found a good solution for this. 我为此找到了一个很好的解决方案。 I used t4mvc for my project and updated all my magic strings. 我将t4mvc用于我的项目,并更新了所有魔术字符串。 I thought this solution would be useful for few developers who have issues with paths. 我认为该解决方案对很少遇到路径问题的开发人员很有用。

This way we can use Url.Content() few example code i added that may help others. 这样,我们可以使用Url.Content()添加的一些示例代码可能会对其他人有所帮助。

<p>This link goes to my `<a href="@Url.Content("~/")">`Application home page</a>.</p>

<p>Now let’s link to a view `<a href="@Url.Content("~/Controller/Action")">`in the Controller/Action directory</a>.

Url.Content("~/img/myImage.png")

<img src= "@Url.Content(Model.ImagePath)" alt="Sample Image" style="height:50px;width:100px;"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM