Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could i call a javascript function within the view of my ASP MVC application

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?

like image 688
Abhishek Maurya Avatar asked Jan 28 '16 17:01

Abhishek Maurya


1 Answers

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>
like image 62
Shyju Avatar answered Sep 22 '22 01:09

Shyju