Upgrading Table Models with ASP.NET MVC 3 and Ajax

Trying to update a record list using ajax, displayed in a table where each record has a JavaScript delete link. When I load the table initially, the RemoveLink functions correctly. However, once the div "RecordListPartialView" is updated via ajax, it stops working.

Checking with Firebug, the generated HTML code appears correct for each row. It seems that the browser is not recognizing the new code and therefore not triggering the JavaScript links.

Could someone please explain what might be causing this issue?

(1) View Code:

$(".RemoveLink").click(function () {
    var _id = $(this).attr("data-id");
    var recordToDelete = { id: _id };
    var json = $.toJSON(recordToDelete);
    $.ajax({
        url: '/MortagePayment/RemoveMortageRecord',
        type: 'POST',
        dataType: 'json',
        data: json,
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            $("#RecordListPartialView").empty();
            $("#RecordListPartialView").html(data.Message);
        }
    });
});
$(".AddLink").click(function () {
    var _year = $("#NewRecord_year").val();
    var _month = $("#NewRecord_month").val();
    var _mortageValue = $("#NewRecord_mortageValue").val();
    var newRecord = { year: _year, month: _month, mortageValue: _mortageValue };
    var json = $.toJSON(newRecord);
    $.ajax({
        url: '/MortagePayment/AddMortageRecord',
        type: 'POST',
        dataType: 'json',
        data: json,
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            $("#RecordListPartialView").empty();
            $("#RecordListPartialView").html(data.Message);

            $("#NewRecord_year").val(0);
            $("#NewRecord_month").val(0);
            $("#NewRecord_mortageValue").val(0);
        }
    });
});
<div id="RecordListPartialView">
    @Html.Partial("MortageRecordList", Model.MortageRecordList)
</div>

(2) Partial View:

<table id="mortageRecordListTable">
    <tr>
        <th colspan=4>Current reductions</th>
    </tr>
    <tr>
        <th>Year</th>
        <th>Month</th>
        <th>Value</th>
        <th></th>
    </tr>

    @foreach (var item in Model) {
        <tr id="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="10627f673d507964757d3e7d7f62647177754275737f62745974">[email protected]</a>">
            <td>
                @item.year
            </td>
            <td>
                @item.month
            </td>
            <td>
                @item.mortageValue
            </td>
            <td>                
                <p class="RemoveLink" data-id="@item.mortageRecordId">Remove</p>
            </td>
        </tr>
    }              
</table>

(3) Controller:

[HttpPost]
public ActionResult AddMortageRecord(MortageRecord newRecord) {
    var mortageRecordSet = MortageRecordSet.GetMortageSet(this.HttpContext);
    if (ModelState.IsValid) 
        mortageRecordSet.AddMortageRecord(newRecord);
    string partialViewHtml = RenderPartialViewToString("MortageRecordList", mortageRecordSet.GetMortageItems());

    return Json(new { Success = true, Message = partialViewHtml });
}

[HttpPost]
public JsonResult RemoveMortageRecord(int id) {
    var mortageRecordSet = MortageRecordSet.GetMortageSet(this.HttpContext);
    mortageRecordSet.RemoveMortageRecord(id);              
    string partialViewHtml = RenderPartialViewToString("MortageRecordList", mortageRecordSet.GetMortageItems());

    return Json(new { Sucess = true, Message = partialViewHtml });
}

Answer №1

It appears that my understanding is correct.

Upon preloading the table, the RemoveLink functions as expected. However, once the "RecordListPartialView" div is updated via ajax, the functionality ceases to work.

To resolve this issue, consider replacing your .click event with .live

$(".RemoveLink").live("click",function(){
    //insert any necessary click event code here
});

Answer №2

It appears that reinvoking the click handler may be necessary to properly reattach it to the updated DOM elements. This is because jQuery loops through all elements matching the specified class when the $(".RemoveLink").click() and $(".AddLink").click() functions are actually called, rather than on each individual click event.

Answer №3

Are you currently utilizing a jQuery event within a distinct .js script file and have connected an event to an element inside a PartialView?

If so, whenever the PartialView refreshes itself (regardless of the cause), all associated events will be lost! It is necessary to rebind the events after the PartialView has been refreshed.

There are various methods you can use:

  1. Within the Ajax.ActionLink (or any ajax call that triggers the PartialView to refresh), designate OnSuccess to a jQuery function that re-establishes the PartialView's events.

  2. Transfer all your jQuery event binding codes from the separate .js script file to within your PartialView's file (cshtml). In this scenario, every time the PartialView is refreshed, these events will be bound once more.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disabling a specific tab in an array of tabs using Angular and Typescript

Displayed below are 5 tabs that can be clicked by the user. My goal is to disable tabs 2 and 3, meaning that the tab names will still be visible but users will not be able to click on them. I attempted to set the tabs to active: false in the TypeScript fi ...

Pop-up message on card selection using JavaScript, CSS, and PHP

I have a total of 6 cards displayed in my HTML. Each card, when clicked, should trigger a modal window to pop up (with additional information corresponding to that specific card). After spending a day searching for a solution online, I've come here s ...

Border becomes dashed when dragging and dropping

I am working on enabling drag and drop functionality for users. When an item is lifted from its original position, a gray dashed box should appear in its place. As the item is moved closer to another spot, the containers adjust to create a target area (gra ...

Modify the current link's <li> class

I am facing an issue with the code below which is supposed to change the class of li based on whether the browser URL matches the href attribute within that li. The current problem I am encountering is that the code changes the class for all li elements, ...

The display message in Javascript after replacing a specific string with a variable

I'm currently working on a task that involves extracting numbers from a text input, specifically the first section after splitting it. To test this functionality, I want to display the result using an alert. The text input provided is expected to be ...

Angularjs: a powerful tool for passing data efficiently between controllers

In my angular.js application, I have implemented multiple views and I am in need of maintaining the status across view changes. To achieve this, I have created a simple factory to share data between controllers. Instead of using "$scope" in the controllers ...

Does Parsley.js offer a way to configure so that the parsley-success field is not added to an input if it should be completely ignored?

Currently, I am excluding one input and adding the success class (which is fine with me) $('form').parsley({ excluded: '[data-parsley-sum-total="all"]' }); However, there are several other inputs without any validations that I do not wa ...

Alerts for drop down menu validation with multiple buttons

My goal is to design a multi-step form that collects user information. This form consists of 5 stages: Step 1: User details (Name, email, phone, age, gender) Step 2: Yes or No question Step 3: Yes or No question Step 4: Yes or No question Step 5: Yes o ...

Tips on accessing form input values with HttpServletRequest in Java servlets

Okay, I have a bit of a newbie question here. I've been trying to debug this issue for hours now and can't figure out what's going wrong. I'm attempting to submit a form using ajax, then in my controller, I want to parse the input value ...

How to modify the content type in an Angular.js $http.delete request

When making a $http.delete request in my Angular app, I include a config object using the following approach: return $http.delete('projects/' + projectID + '/activityTypes', {data: [{id: 2}]}) This method attaches the values from my d ...

What is the best way to display a single instance of a React component that is declared in multiple locations within the app?

Imagine I have 2 main components, A and B. Now, component C needs to be created inside both A and B. How can I guarantee that the same exact instance of C is generated in both places? Essentially, I want them to stay synchronized - any changes made to one ...

What are some strategies for improving the speed of searching through an array of objects?

I've been exploring more efficient ways to search through an array of objects as my current approach is too slow. The array I'm working with has the following structure: [ { fname: 'r7942y9p', lname: 'gk0uxh', em ...

A clock for counting down on statically produced websites

It seems that I have encountered a limitation of statically generated sites. Currently, I am utilizing Gatsby to generate pages in a static manner. The process involves: Pulling data from the CMS where we set an end time for a countdown timer, such as two ...

What methods can be used to create data for the child component?

Below is the primary code: import {Col,Container,Row} from 'react-bootstrap'; import {useEffect,useState} from "react"; import AppConfig from '../../utils/AppConfig'; import BB from './BB'; import React from "re ...

The error message "Attempting to send a message using an undefined 'send' property in the welcomeChannel" is displayed

bot.on('guildMemberAdd', (member) => { console.log(member) const welcomeChannel = member.guild.channels.cache.find(channel => channel.name === 'welcome'); //const channelId = '789052445485563935' // welcome c ...

What is a way to merge all the letters from every console.log result together?

I'm encountering an issue - I've been attempting to retrieve a string that provides a link to the current user's profile picture. However, when I use console.log(), the output appears as follows: Console Output: https://i.sstatic.net/70W6Q ...

Looping through multiple Ajax requestsIn this scenario, we need

Here's the snippet of code I'm working with: for (var i = 0; i < 20; i++) { $.ajax({ type: "GET", async: false, url: "/MyController/MyMethod", success: function (data) { if (i == 0) { $('#result_progre ...

Pressing the "Enter" key will submit the contents of

Hello, I have recently created a new chat box and everything seems to be working fine. However, I am facing an issue with submitting a message when I press enter (to go to the function Kucaj()). Can anyone provide assistance with this problem? I tried ad ...

Angular has trouble displaying information across multiple HTML files

I have created an HTML file to display some data. The initial HTML file named disc-log.html looks like this: <div> <h2>Discs</h2> <jhi-alert></jhi-alert> <div class="container-fluid"> <div class=" ...

How to link a CSS file from a JavaScript file

I have a form for users with fields for first name, last name, password, and confirm password. I've implemented validation to check if the password and confirm password fields match using JavaScript: $(document).ready(function() { $("#addUser").cl ...