I have a view that has some jQuery to load a partial view (via a button click) into a div in the view. This works without a problem. However within the partial view I have a very similar bit of jQuery that will load another partial view into a div in the first partial view, but this isn’t working, it almost seems like the jQuery in the first partial view isn’t being loaded.
I have tried searching for solutions, but I haven’t managed to find an answer. I have also re-created the jQuery function in a @Ajax.ActionLink which works fine, however I am trying to avoid the Microsoft helpers as I am trying to learn jQuery.
Here is the first partial view which contains the jQuery that doesn’t seem to work, it also contains the @Ajax.ActionLink that does work:
@model MyProject.ViewModels.AddressIndexViewModel
<script>
$(".viewContacts").click(function () {
$.ajax({
url: '@Url.Action("CustomerAddressContacts", "Customer")',
type: 'POST',
data: { addressID: $(this).attr('data-addressid') },
cache: false,
success: function (result) {
$("#customerAddressContactsPartial-" + $(this).attr('data-addressid'))
.html(result);
},
error: function () {
alert("error");
}
});
return false;
});
</script>
<table class="customers" style="width: 100%">
<tr>
<th style="width: 25%">
Name
</th>
<th style="width: 25%">
Actions
</th>
</tr>
</table>
@foreach (Address item in Model.Addresses)
{
<table style="width: 100%; border-top: none">
<tr id="address-id-@item.AddressID">
<td style="width: 25%; border-top: none">
@Html.DisplayFor(modelItem => item.Name)
</td>
<td style="width: 25%; border-top: none">
<a href="#" class="viewContacts standardbutton" data-addressid="@item.AddressID">ContactsJQ</a>
@Ajax.ActionLink("Contacts", "CustomerAddressContacts", "Customer",
new { addressID = item.AddressID },
new AjaxOptions { UpdateTargetId = "customerAddressContactsPartial-" + @item.AddressID, HttpMethod = "POST" },
new { @class = "standardbutton"})
</td>
</tr>
</table>
<div id="customerAddressContactsPartial-@item.AddressID"></div>
}
If someone could explain what I am doing wrong here and how to fix it then I would be very grateful.
Thanks very much.
In case you didn’t know, in ASP.NET MVC 3, Ajax.* helper use jQuery, contrary to ASP.NET MVC 2 where they were using Microsoft Ajax scripts. Also it is considered bad practice to put javascript code in your views and partial views.
I would recommend you externalizing this in a separate javascript file inside a function.
You haven’t shown how you rendered this partial, I guess you used AJAX again, so in the
successcallback of this AJAX call once you inject the partial into the DOM you invoke theajaxifyViewContactsLinkfunction.Now your partial simply contains what it should contain – markup: