Monzingo
Monzingo

Reputation: 411

Razor variable used within more Razor within Javascript

Im looping through multiple items and setting an image tag like below for each item. Each one has an onmouseover and onmouseout event. The db stores both mouseover and mouseout image directories separated by a semicolon. This part is functioning fine.

<img onmouseover="hover(this, @id);" onmouseout="unhover(this, @id);" src="@(tblIconTable.getSpecificIconFromId(id).icon.Split(';')[0])" />

The issue is when i get to my javascript events

function hover(element, Id) {
    element.setAttribute('src', '@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[1])');
}
function unhover(element, Id) {
    element.setAttribute('src', '@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[0])');
}

The 'Id' i am using here within more razor within javascript is not being recognized. Is there a clever work around for this?

Upvotes: 0

Views: 38

Answers (1)

James
James

Reputation: 22246

One way to approach this is by assigning the two urls as data- attributes to each img tag, and then reading those attributes within the hover/unhover functions:

<img onmouseover='hover(this)' onmouseout='unhover(this)' data-img-hover='@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[1])' data-img-unhover='@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[0])' src='@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[0])'>

function hover(element) {
    element.setAttribute('src', element.data('img-hover'));
}
function unhover(element) {
    element.setAttribute('src', element.data('img-unhover'));
}

Upvotes: 1

Related Questions