0

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

10
  • How are you setting the data-url? Commented Apr 22, 2015 at 13:17
  • A "GET" form will append this to the URL using the global.aspx page won't it? Are you not using a form to populate this URL Commented Apr 22, 2015 at 13:17
  • JavaScript and Serverside code do NOT run at the same time. Commented Apr 22, 2015 at 13:18
  • When and how do you set the value of the JavaScript variable? Does the variable have the value at the time that the HTML code is parsed? Commented Apr 22, 2015 at 13:23
  • @epascarello I understand there is a mix of client and server code here but there are way around that, please don't comment "can't be done" because you don't know how to do it. Commented Apr 22, 2015 at 13:54

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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>

1 Comment

thank you, this does set the data-url attribute, but my problem is the page loads, then the attribute is set so it doesn't update my div with the appropriate data. How can I refresh the partial view?
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.