bankey bankey - 1 year ago 81
jQuery Question

MVC - Partial View for Layout loads, but does not trigger javascript

My shared page layout,


<div class="navbar-collapse collapse">


<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Hello, " + User.Identity.Name + "!", "UserProfile", "Home")</li>
<a href="~/ShoppingCart/Index" id="ShoppingCartSpace"><i class="fa fa-shopping-cart" aria-hidden="true" id="ShoppingCartIcon"></i></a>
<span class="badge" id="BadgeIcon"></span>
<a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>

The BadgeIcon is what I want to display in every View, so I made a script that would take the current user's shopping cart from database, calculate the total cart quantity on the fly, and then .ajax the return in the

The script located at the end of

@section scripts
<script> //never gets triggered

$(document).ready(function () {
type: "POST",
url: '@Url.Action("getCartCount", "ShoppingCart")',
success: function (data) {


Also posting this snippet from the ShoppingCartController:

public ActionResult getCartCount()
var user = db.Users.FirstOrDefault(x => x.UserName == HttpContext.User.Identity.Name);
var cartCount = user.ShoppingCarts.FirstOrDefault().ShoppingCartProducts.Sum(x => x.Quantity);

return Json(cartCount);

As you may tell, I am far from an expert on MVC, so any help on this would be greatly appreciated.

Answer Source

Posting the answer which was found by Pravin Tukadiya and Jasen:


<script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script> <script src="~/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>

to _LoginPartial.cshtml and removed

@section scripts{
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download