What could be causing the malfunction of the delete button in my app?

I've been trying to implement a delete button in my code to remove certain entries from a model. However, I keep encountering an error that I can't seem to troubleshoot. My controller includes an IActionResult called `deletelname`, and everything appears to be logically sound, but the functionality is not working as expected. I would greatly appreciate it if someone could review the code and provide some feedback.

Here's how the view looks:

@model IEnumerable<Models.pinfo>
@using Models
@foreach (var s in Model){

    <h1> @s.fname  @s.lname </h1> <h3> @s.comment </h3> <a class="GoDelete" href="javascript:void(0)" data-id="@s.lname">Delete</a>

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myModalLabel">Deleting....</h4>
                </div>
                <div class="modal-body">
                    Are you sure you want to Delete this Entry?
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button id="btndelete" type="button" class="btn btn-primary">Delete</button>
                </div>
            </div>
        </div>
    </div>

}

@section scripts
{
    <script>
        $(document).ready(function() {
            $("#btndelete").click(function () {
                $('#myModal').modal('hide');
                var id = $('#hfId').val();
                window.location.href = '@Url.Action("deletelname","Home")/'+id;
            });

            $(".GoDelete").click(function () {
                var id = $(this).attr("data-id");
                $('#hfId').val(id);
                $('#myModal').modal('show');
            });

        });
    </script>


}

Snippet of the Controller method:


public IActionResult deletelname(pinfo pinfo)
{

    var fsname = db.pinfo;
    var lsname = db.pinfo;
    var csomment = db.pinfo;

    foreach (var fname in fsname)
    {
        db.Remove(fname);
    }

    foreach (var lname in lsname){
        db.Remove(lname);
    }

    return View("Contact", "Home");
}

Whenever I attempt to use the delete button, I encounter the following error message:

Answer №1

The reason for the error message is due to passing the string "Home" as the model for the view "Contact" when an enumerable object of type Model.pinfo is expected.

Consider returning the pinfo object from the controller when rendering the view, although it may not produce the desired outcome, it aligns with what you are seeking.

    public IActionResult deletelname(pinfo pinfo)
    {

        var fsname = db.pinfo;
        var lsname = db.pinfo;
        var csomment = db.pinfo;

        foreach (var fname in fsname)
        {
            db.Remove(fname);
        }

        foreach (var lname in lsname){
            db.Remove(lname);
        }

        return Contact();
    }

Please note that there are also issues with the Javascript code:

$("#btndelete").click(function () {
    $.ajax({
        url: '@Url.Action("deletelname","Home")',
        method: 'POST',
        data: { pinfo: $('#hfId').val() },
        success: function (response) {
            // this code gets executed after a successful request
            // according to the controller method written, the response should be the re-rendered "Contact" view HTML.
            console.log(response);

            // In case of an error, avoid closing the modal unless the operation is successful
            $('#myModal').modal('hide');
        },
        error: function (response) {
            // runs in case of an error
            console.log(response);
        }
    });
});

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

The TypeScript compiler is generating node_modules and type declaration files in opposition to the guidelines outlined in the tsconfig.json file

For the past week, I've been trying to troubleshoot this issue and it has me completely puzzled. What's even more puzzling is that this app was compiling perfectly fine for months until this problem occurred seemingly out of nowhere without any c ...

"Troubleshooting: The Dropzone js code sample from the documentation

I am currently implementing a tutorial from the documentation provided by Dropzone.js. However, I seem to be encountering an issue as the example is not working correctly. Here is the structure that I currently have: Dropzone.options.myAwesomeDropzone = ...

Tips for displaying animations only the first time using HTML and CSS:

Upon the initial visit to my website, a captivating animation introduces itself with the words "Hello. I'm Bob" as it gracefully fades into view. Navigating through the menu bar allows users to explore different sections of the site. However, there ...

Ways to avoid data looping in jQuery Ajax requests

This is in relation to the assignment of multiple users using the Select2 plugin, Ajax, and API. The situation involves a function that contains 2 Ajax calls with different URLs. Currently, there are pre-selected users stored in the database. The selection ...

Tips on accessing JSON keys with AngularJS ng-repeat function?

Looking to iterate through a JSON object in Angular and retrieve the keys Testing01, Testing02, and Testing03 using ng-repeat directive. Any suggestions on how to achieve this would be greatly appreciated. Thank you in advance. Access the Fiddle here. ...

Is there a way to prevent the React history.push from reloading the component every time? I only want

After loading a component and redirecting using history.push, my component renders twice, triggering the componentDidMount() function twice as well. Below is a simplified version of my component. Everything runs fine with componentDidMount() running only ...

Tips for modifying the background color of a specific line within a RichTextBox

Is it possible to change the color of the entire line, even if there is no text present? See the visual explanation below: . While I did find a solution here, I am hoping for a simpler alternative. ...

How can I use JavaScript to loop through a specific attribute?

I have implemented ckeditor inline on a website I created. While it allows me to save data to a database, the issue arises when ckeditor automatically applies its own classes and attributes to certain elements where contenteditable is enabled. It also re ...

What is the best way to patiently wait for the serial port to finish reading?

I need to transfer data from a device to my PC to display in a data grid view. However, I am having trouble waiting for the serial port to completely receive the data. Even after using code that should work, it still doesn't seem to function properly. ...

Troubleshooting Problem with Retrieving Files Using jQuery Ajax

I am attempting to use ajax to retrieve the contents of a file, but it doesn't seem to be functioning properly. I'm not sure why this is happening, as I have copied the same code from the examples on w3schools.com. $().ready(function(){ ...

Rotating Camera around a Vector3 Point in Three.js

Let me get straight to the point - math is not my strong suit. What may be a piece of cake for you is like solving complex equations in outer space for me. Currently, I am using Three.js with CSS3DRenderer to construct a virtual art gallery. What I reall ...

Executing PHP code from Javascript - Using AJAX to retrieve full HTML content of the webpage

As someone who is still getting to grips with PHP, I have been exploring ways to call a PHP method from a button. It seems that one approach involves assigning the button's onclick event to trigger a JavaScript function, which then uses Ajax to post t ...

Having trouble loading HDRI image as environment using Three.js

I recently started using Three.js and am currently tackling a project that involves utilizing an HDRI file for environmental mapping for lighting and reflection purposes. I've been experimenting with loading HDRI files using the HDRCubeTextureLoader a ...

The trio of Selenium Internet Explorer Driver, Kendo Mobile, and Octopus Deploy are a powerful combination

Our team has developed an MVC 5 C# web application that utilizes Kendo Mobile UI components. We use Octopus Deploy to deploy the application to Test, Staging, and Production environments, with a step dedicated to running Selenium UI tests. While everythin ...

The module.run function in Angular is invoked with each individual unit test

Hey there I am currently working on setting up jasmine-karma unit tests for my angular app. The problem arises in my app.js file where the module.run method is calling a custom service (LoginService) that then makes a call to the $http service. The issue ...

What is the best way to provide a String as input to a Google Cloud Function?

I am in need of a Google Cloud Function that can be called from my Android application. The function's purpose is to invoke the Vision API Safe Search and provide the results back to the app. The issue at hand: The current function I have is function ...

Launch target _blank within a modal instead of a new tab

I'm currently exploring ways to use vanilla JavaScript in order to display all external links - particularly those that typically open in a new tab or window - within a modal box instead. My goal is to implement a listener on external links (those no ...

Pass information to a Bootstrap modal for processing and execute a MySQL database query

while($row = mysqli_fetch_array($result_from_query)){ <a class="modal-trigger" href="#basicModal" data-toggle="modal" data-target="#basicModal" data-id="<?php echo $row['invoice_no']; ?>"><?php echo $row['invoice_no&ap ...

Encountering difficulties with uploading files and images in a Node.js environment

Currently, I am learning node js and express js on Tutorial Point. In the course, I attempted to upload a document but encountered an error that says "Cannot read property 'file' of undefined." Can someone please assist me in resolving this issue ...

Obtaining the camera's rotation in radians using Three.js

I've been struggling to grasp the concepts of quaternions for quite some time now, and I suspect they may be the root cause of my current challenge. If you're familiar with three.js, you might know about the equirectangular panorama video exampl ...