9

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?

1
  • You don't have a closing bracket for your func function Commented Jan 28, 2016 at 17:17

1 Answer 1

11

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>
Sign up to request clarification or add additional context in comments.

1 Comment

thanks very much Shyju. It worked. A very very thanks. I was really stuck up.

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.