XN16
XN16

Reputation: 5879

JQuery within a partial view not being called

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="[email protected]">
            <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="[email protected]"></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.

Upvotes: 1

Views: 4100

Answers (4)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

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.

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.

function ajaxifyViewContactsLink() {
    $('.viewContacts').click(function () {
        $.ajax({
            url: this.href,
            type: 'GET',
            cache: false,
            context: this,
            success: function (result) {
                // see the updated markup of the partial below
                // that works with this:
                $(this).closest('.address')
                       .find('.results')
                       .html(result);
            },
            error: function () {
                alert("error");
            }
        });
        return false;
    });
}

You haven't shown how you rendered this partial, I guess you used AJAX again, so in the success callback of this AJAX call once you inject the partial into the DOM you invoke the ajaxifyViewContactsLink function.

Now your partial simply contains what it should contain - markup:

@model MyProject.ViewModels.AddressIndexViewModel
<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)
{
    <div class="address">
        <table style="width: 100%; border-top: none">
            <tr id="[email protected]">
                <td style="width: 25%; border-top: none">
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td style="width: 25%; border-top: none">
                    @Html.ActionLink(
                        "ContactsJQ", 
                        "CustomerAddressContacts", 
                        "Customer",
                        new { addressid = item.AddressID },
                        new { @class = "viewContacts" }
                    )
                </td>
            </tr>
        </table>
        <div class="results"></div>
    </div>
}

Upvotes: 1

Qpirate
Qpirate

Reputation: 2078

You are missing the

$(function(){
//code goes here
})

around the script. the page doesn't realise that there is jquery to be executed.

EDIT

you could use an eval on the script that is returned. like the following. kindof a hack i know but still should get you working.

    function (data, textStatus, jqXHR)
            {
                var $scripts = undefined;
                if ($(data).has('script'))
                {
                    $scripts = $(data).filter('script');
                }
                //APPEND YOUR HTML To the page. then run the scripts that are contained.

                if ($scripts != undefined)

                    $scripts.each(function ()
                    {
                        if ($(this).attr('src') != '' && $(this).attr('src'))
                            $.getScript($(this).attr('src'));
                        else
                            eval(this.innerHTML || this.innerText);
                    });

            };

this would be the success function of the ajax call

Upvotes: 1

Adder
Adder

Reputation: 5868

You have to re-attach the click handler to the newly loaded element everytime you reload the element over ajax.

Upvotes: 1

Rajpurohit
Rajpurohit

Reputation: 1991

In controller i have action .

public ActionResult ShowAllState()
        {
            return PartialView("_State", CityRepository.AllState);
        }

"_State" Is my partial view .

In view i have button . when i click on this button then my partial view lode all state data.

<h5>
    Page Lode With Jquery</h5>
<input type="button" value="Lode Form" id="btnLode" />

<script type="text/javascript">
    $(function () {
        $("#btnLode").click(function () {
            $("#LodeForm").load("/City/ShowAllState", function () {
                alert("Your page loaded Successfully !!!!!!!");
            });
        });
    });

</script>

<div id="LodeForm">
</div>

i lode all my state data in "LodeForm" div .

i think this well help you....

Upvotes: 1

Related Questions