Javascript Variable in Url.Content

2019-08-31 07:08发布

问题:

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:

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. How can I achieve this??

回答1:

You cannot use the Javascript variable directly into attribute. A workaround can be to reorder the parameters of your url and setting the JavaScript variable in script tag.

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

I have reordered the url parameters here. The location parameter will be set by following script. Place this script just after the button element.

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


回答2:

The problem here is @url.content needs to be run on server, where JavaScript variable is not visible. Write an independent AJAX call to fetch content and than set content in data-url



回答3:

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

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