bankey bankey - 4 months ago 15
jQuery Question

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

My shared page layout,

_CustomerLayout.cshtml
has:

<div class="navbar-collapse collapse">
@Html.Partial("_LoginPartial")
</div>


The
_LoginPartial.cshtml
has:

<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Hello, " + User.Identity.Name + "!", "UserProfile", "Home")</li>
<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>
</li>
<li>
<a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>
</li>
</ul>


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
#BadgeIcon
div

The script located at the end of
_LoginPartial.cshtml
is:

@section scripts
{
<script> //never gets triggered

$(document).ready(function () {
$.ajax({
type: "POST",
url: '@Url.Action("getCartCount", "ShoppingCart")',
success: function (data) {
$('#BadgeIcon').html(data);
}
})
});

</script>
}


Also posting this snippet from the ShoppingCartController:

[HttpPost]
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

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

Added

<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{
}
Comments