I have the following JavaScript function in my view page :
<script type="text/javascript">
function func(nam) {
alert(nam);
</script>
My view code for calling this function goes like this on the same page:
@foreach (var item in Model)
{
<script>func(@item.name) </script>
}
It does not produce any result.
I need to call the JavaScript function from within html but it is not happening. Kindly help me through it.
Is there any other way of calling the JavaScript function?
Assuming your item.Name
property has a string value SomeThing
.So when razor render your page, your generated markup will be
<script> func(SomeThing) </script>
Now the javascript engine thinks that SomeThing
is a js variable. But we do not have a js variable with that name defined and intialized earlier. So you might see a script error saying
SomeThing is not defined
You need to pass the parameter as a string literal. Wrap it with single quotes or double quotes.
<script>func('@item.name') </script>
Also you need to make sure that func
javascript method is defined before you try to execute the method.
<script>
function func(nam) {
alert(nam);
}
</script>
<script>func('@item.Name') </script>
If the function is inside an external js file, you need to make sure to include/load it before executing the method.
<script src="~/Scripts/YourJsFileWherFuncIsDefined.js"></script>
<script>func('@item.Name') </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With