Monday, September 5, 2011

Adding jQuery to an MVC view

To add jQuery code in an MVC view, we need to write its code in the head section of the view. The example below shows simple jQuery code written in an MVC view.

<head>
<script type="text/javascript">
$(document).ready(function ()
{

// here we can write any javascript code that will be executed as soon as the page loads  

// If we have a dropdown in our page, named as "xyz", and need to write code that executes when it's value is changed to "1", we could do the following:

$('#xyz').change(function ()
{
if ($('#xyz').val() == "1")
{

// over here we can write code that will execute when the value "1" is selected in the dropdown "xyz"

}
else if ($('#xyz').val() == "2")
{


// over here we can write code that will execute when the value "2" is selected in the dropdown "xyz"                

}

});
});
</script>

 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

</head>

No comments:

Post a Comment