C
C#3w ago
Zee

can you call a function in a partial_view?

so I am makign this pharmaceutical mvc app and I for some reason when I do a view Page source it says It cant find my script. so am i allowed to run a script in a partial view I would assume so since its only a naming convention
7 Replies
Angius
Angius3w ago
What's the exact error? And does the JS code exist in the generated site code?
Zee
ZeeOP3w ago
ah dman when I did page inspect It was just that it could not find the function PurchaseProduct(productName) I ended up removing that bit of code
Angius
Angius3w ago
Could be because the function is declared after it's being used One of the reason you should use .addEventListener() instead of onclick
Zee
ZeeOP3w ago
yh I tried adding it before the html but still an erorr .addEventListener(PurchaseProduct()); like that but generally speaking can you call scripts in a partial view I thought maybe the injection in the Index.cshtml was messing things up since thats done by a javascript function too
Angius
Angius3w ago
No, not like that And yes, you can use JS in partial views
<button id="foo">Click</button>
<button id="foo">Click</button>
document
.getElementById('foo')
.addEventListener('click', PurchaseProduct);
// or
.addEventListener('click', () => PurchaseProduct());
document
.getElementById('foo')
.addEventListener('click', PurchaseProduct);
// or
.addEventListener('click', () => PurchaseProduct());
To get some data:
<button id="foo" data-name="@Model.ProductName">Click</button>
<button id="foo" data-name="@Model.ProductName">Click</button>
document
.getElementById('foo')
.addEventListener('click', (e) => {
const name = e.currentTarget.dataset.name;
PurchaseProduct(name);
});
document
.getElementById('foo')
.addEventListener('click', (e) => {
const name = e.currentTarget.dataset.name;
PurchaseProduct(name);
});
Zee
ZeeOP3w ago
thx

Did you find this page helpful?