CodeDigest.Com Logo
Featured:

How to Call JavaScript Functions in Asp.Net MVC Views ?

Tagged as: Asp.Net MVC JavaScript jQuery Posted By

Gone are days where we have developed web application with only server side technologies and used scripting language like JavaScript very minimally for some client side validations. Web applications these days are primarily developed using various JavaScript frameworks and it uses server technologies only for service development and for integration with other systems, etc. This means if you are web developer then JavaScript is a default skill you should possess. This is a beginner article which will help you to use JavaScript and jQuery library in Asp.Net MVC project.

Calling JavaScript Function from Razor View

Assume, you have a list of employee displayed in HTML table and you want to call a javascript function on click of the employee name column. For simplicity, we will display an alert box with the name of the employee you have clicked.

 

 

To include a JavaScript function, it is as simple as include a <script> tag and define the function inside the script block. Now, to call the function, add an onclick event on the employee name hyperlink and call the function. The below code does that. The JavaScript function AlertName() takes a input parameter name to pass the employee name during the onclick event.

 

<script type="text/javascript">

function AlertName(name)

{

alert('You clicked '+ name +"!");

}

</script>

<div>

    <table class="table table-bordered table-condensed">

        <tr>

            <th>Name</th>

            <th>Department</th>

            <th>Action</th>

        </tr>

        @foreach (Employee emp in Model)

        {

            <tr>

                <td>

                    <a onclick="AlertName('@String.Format("{0} {1}", emp.FirstName, emp.LastName)')" href="#">@String.Format("{0} {1}", emp.FirstName, emp.LastName)</a>   

                </td>

                <td>

                    @emp.Department.DepartmentName

                </td>

                <td>@Html.ActionLink("Edit", "edit", new { id = emp.EmployeeId })</td>

            </tr>

        }

    </table>

</div>

 

When executed, you can see the JavaScript function getting called on click of employee name hyperlink. Though, it is working it is not a good practice to include the <script> block with JavaScript function just anywhere in the razor view as we did above. The recommended approach is to put in a separate JavaScript file or inside a section defined in Layout page.

Adding a Layout Section for script

A section can be added in the MVC Layout page using @RenderSection() directive. For example, we can define a section in Layout page under <head> tag for scripts like below.

_Layout.chtml

 

DOCTYPE html>

<html>

<head>

       //Removed for brevity

       @RenderSection("scripts", required: false)

</head>

 

The required:false setting in @RenderSection directive will make the script section in the content views optional. Set it to true to make it mandatory.

We can now define a section named “scripts” using @section directive in the content views to include our JavaScript functions. So, the <script> block in our previous example can be included in @section directive in the content view like below.

EmployeeSummary.cshtml

 

@section scripts {

<script type="text/javascript">

    function AlertName(name)

    {

        alert('You clicked '+ name +"!");

    }

</script>

}

 

When executed, the scripts included in @section in the content views will be placed under <head> tag in the output HTML generated by the Asp.Net MVC.

Using jQuery in Asp.Net MVC View

Let’s see how to use jQuery library to display alert box similar to our previous example which used JavaScript function. We need to first download and include latest jQuery library into our layout page. You can use Nuget package manager to download and copy jQuery library into our solution. The layout page with jQuery library below.

_Layout.cshtml

<!DOCTYPE html>

<html>

<head>

     //Removed for brevity

    <script src="/Scripts/jquery-3.1.1.min.js"></script>

    @RenderSection("scripts", required: false)

</head>

 

The content razor view with jQuery script section below.

EmployeeSummary.cshtml

 

<div>
    <table class="table table-bordered table-condensed">
        <tr>
            <th>Name</th>
            <th>Department</th>
            <th>Action</th>
        </tr>
        @foreach (Employee emp in Model)
        {
            <tr>
                <td>
                    <a href="#">@String.Format("{0} {1}", emp.FirstName, emp.LastName)</a>
                </td>
                <td>
                    @emp.Department.DepartmentName
                </td>
                <td>@Html.ActionLink("Edit", "edit", new { id = emp.EmployeeId })</td>
            </tr>
        }
    </table>
</div>

@section scripts {

<script type="text/javascript">

    $(document).ready(function(){

        $('table a').click(function () {

                alert('You clicked '+ name +"!");

        });

    });

</script>

}

 

When executed, you will get the alert box with the name of the employee. Please make sure you have placed the jQuery library <script src="..."></script> tag before @RenderSection directive in Layout page.

Happy Coding!!



Feedback

Comments

js file
How would I proceed if I want to put my javascript code in a separate file and then use it in my view? How to link the two files? Thanks
Commented by Will on 1/14/2021 9:09:28 AM

JQuery example
$('table a').click(function () { alert('You clicked '+ name +"!"); }); In JQuery example, alert(name) will be empty. We need to use this.text to get the name of employee name
Commented by ray on 3/5/2020 3:58:03 AM

name
nope
Commented by hahaha on 2/23/2020 11:34:56 PM