Url.Content中的Javascript变量



我有一个名为locid的javascript变量,我试图通过设置div的数据URL来将其用作URL的一部分,如下所示:

data-url='@Url.Content("~/Catalogue_Items/ItemsActionViewPartial/")@Model.CatItemID?LocationID=locid&AsyncUpdateID=catalogue-view'>

我知道我不能像在示例代码中那样将 locid 扔到该字符串中,但我只是把它放在那里来说明我需要我的 javascript 变量在哪里。 我怎样才能做到这一点??

这里的问题是@url.content需要在服务器上运行,其中JavaScript变量不可见。编写一个独立的 AJAX 调用来获取内容,然后在数据 url 中设置内容

你不能直接在属性中使用 Javascript 变量。解决方法是重新排序 url 的参数,并在脚本标记中设置 JavaScript 变量。

<button id="myButton" data-url='@Url.Content("~/Catalogue_Items/ItemsActionViewPartial/")@Model.CatItemID?AsyncUpdateID=catalogue-view'></button>

我在这里对 url 参数进行了重新排序。位置参数将通过以下脚本设置。将此脚本放在按钮元素之后。

<script>
var button = document.getElementById('myButton');
var url=button.getAttribute('data-url');
url+="&LocationID=" + locid;
button.setAttribute('data-url',url);
</script>

您可以使用 document.write 将值放入页面中,但不能将其写出标签内,您必须写出整个标签。例:

<script>
document.write('<div data-url="@Url.Content("~/Catalogue_Items/ItemsActionViewPartial/")@Model.CatItemID?LocationID=' + locid + '&AsyncUpdateID=catalogue-view">');
</script>

最新更新