简体   繁体   English

Url.Content中的Javascript变量

[英]Javascript Variable in Url.Content

I have a javascript variable called locid that I am trying to use as part of a URL by setting the data-url of a div as follows: 我有一个名为locid的javascript变量,通过设置div的data-url,尝试将其用作URL的一部分:

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

I know I can't just throw the locid in that string as I have done in my sample code but I just put it there to illustrate where I need my javascript variable to be. 我知道我不能像我在示例代码中那样将locid放入该字符串中,但我只是将其放在此处以说明需要将我的javascript变量放置在何处。 How can I achieve this?? 我该如何实现?

The problem here is @url.content needs to be run on server, where JavaScript variable is not visible. 这里的问题是@ url.content需要在不可见JavaScript变量的服务器上运行。 Write an independent AJAX call to fetch content and than set content in data-url 编写一个独立的AJAX调用以获取内容,然后在data-url中设置内容

You cannot use the Javascript variable directly into attribute. 您不能将Javascript变量直接用于属性。 A workaround can be to reorder the parameters of your url and setting the JavaScript variable in script tag. 一种解决方法是重新排序url参数并在script标签中设置JavaScript变量。

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

I have reordered the url parameters here. 我在这里重新排序了url参数。 The location parameter will be set by following script. location参数将通过以下脚本设置。 Place this script just after the button element. 将此脚本放在button元素之后。

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

You can put the value in the page using document.write , but you can't write it out inside the tag, you have to write out the entire tag. 您可以使用document.write将值放在页面中,但不能将其写到标签内,而必须写出整个标签。 Example: 例:

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

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

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