Steps for invoking a method from a controller

I am currently in the process of developing a website similar to Planning Poker. One issue I am facing is figuring out how to delete games once they have been created. Specifically, I am struggling with calling gamesremoveALL from my controller.

Below is the code snippet that I am having trouble with (taken from my gamelist js file)

 self.removeGames = function () {
    $.getJSON("/data/games/remove", function (d) {
        self.games.RemoveAll(d);
    })
}
};

Here is the remaining sections of my code:

Index( used for creating games)

 <html>

<head>
<title>Planning Poker</title>
<style>
    .inlinetext {
        display: inline;
    }
</style>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script type="text/javascript">
    $(function () {
        $('#button').on('click', function (data) {
            $.post('data/games/create/?title=5', function (d) { console.log(d) });
        })
    });
</script>
</head>



<body>
<h3 class='inlinetext'> Create Game: </h3>
    <input type="text" id="testtext" name="ime">
    <button id="button" >Create</button>


</body>

 </html>

Controller

using PlanningPoker.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace PlanningPoker.Controllers
{
public class GMController : ApiController
{
    private static List<Game> games = new List<Game>() {
            new Game() {
                ID = Guid.NewGuid(),
                Title = "D&D"
            }
        };

    [Route("data/games")]
    public IEnumerable<Game> GetAllGames() {
        return games;
    }

    [Route("data/games/create"), HttpPost]
    public Guid CreateGame(string title) {
        Game g = new Game() {
            ID = Guid.NewGuid(),
            Title = title
        };

        games.Add(g);

        return g.ID;
    }

    [Route("data/games/remove"), HttpPost]
    public void RemoveGame(Guid id) {
        games.RemoveAll(g => g.ID == id);
    }
}
}

GameList (js) This is where I am encountering difficulties.

function AppViewModel() {
var self = this;

self.games = ko.observableArray([]);

$.getJSON("/data/games", function (d) {
    self.games(d);
});


self.removeGames = function () {
    $.getJSON("/data/games/remove", function (d) {
        self.games.RemoveAll(d);
    })
}
};
$(function () {
 ko.applyBindings(new AppViewModel());
 });

Gamelist (html)

 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Game List</title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script src="Gamelist.js"></script>
    </head>
    <body>

            <h4>Games</h4>

            <ul data-bind="foreach: $data.games">
                <li>
                    Game <span data-bind="text: $index"> </span>:
                    <span data-bind="text: Title"> </span>
                    <a href="#" data-bind="click: $parent.removeGames">Remove</a>
                </li>
            </ul>



    </body>
    </html>

Answer №1

$.getJSON("/data/games/remove", function (d) {
    self.games.RemoveAll(d);
})

The current route is set up as a POST route to the CreateGame action, so a getJSON call will not work in this case. To make it functional, change the ajax call to a post method like this:

You also need to include the id value that the action is expecting. Consider modifying the code like so:

$.ajax({
  url: '/data/games/remove',
  type: 'POST',
  data: id,
  dataType: 'json'
}).done(function(response) {
  //do something with response
});

By following these steps, you should be able to successfully interact with the action and handle the removal process accordingly.

Answer №2

In the case of self.games being an observableArray, make sure to use the method name "removeAll" instead of "RemoveAll":

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 form in popover is experiencing issues with jQuery functionality

I need assistance with setting up a form inside a popover that utilizes jQuery and Ajax for form submission with calculations. However, I am facing issues as jQuery seems to not be functioning properly. My project is based on Ruby on Rails. This is the co ...

Expandable Hover Navigation Bar with jQuery for Full Page Width Dimension

I currently have a vertical menu on my website and I am looking to implement a dropdown system for some of the links. I came across an example on the internet that inspired me: http://jsfiddle.net/4jxph/3018/ However, I specifically want a full-width subme ...

Problem with extJS portal functionality

Currently, I am utilizing this particular URL for my application: . I attempted to swap out the existing chart in the third column with a bar chart and a pie chart (both of which work fine within panels and windows), but I encountered an "h is undefined" e ...

"An undefined message will be displayed in AngularJS if there is no content

When the two textboxes are left empty, you will see errors as 'undefined' displayed. These errors disappear once content is entered. The code I have written looks like this: Default.aspx <div ng-app="Welcomecontroller" ng-controller="FullNa ...

Setting up Node.js for production on Nginx: A comprehensive guide

I am working on developing a chat system using angularjs and nodejs. To enable message sending and receiving, I have implemented socket.io. Initially, I set up a node.js server using localhost cmd. Everything is functioning properly, but now I need to dep ...

How to utilize the ItemTemplate control in ASP.NET GridView

I am currently using ASP.NET GridView on my ASPX page: <asp:GridView ID="GrdLimitAndUtilization" runat="server" AutoGenerateColumns="False" GridLines="None" Width="99%" meta:resourcekey="GrdAccountListResource1" OnRowDataBound="GrdL ...

The window.onload function is ineffective when implemented on a mail client

Within my original webpage, there is a script that I have created: <script> var marcoemail="aaaaaa"; function pippo(){ document.getElementById("marcoemailid").innerHTML=marcoemail; } window.onload = pippo; </script> The issue a ...

Sending detailed exception information from asp.net core to the client (such as Angular)

Trying to retrieve exception text from the backend (ASP.NET Core) in an Angular application has been a challenge. Examples have shown the controller action's return type as either JsonResult or ActionResult. In such cases, we can utilize the followi ...

Repetition of UTM Parameters

I created a web page with a donation form embedded in it. Donors visiting the page come through a link that includes a source code at the end. I managed to include this source code in the URL of the embedded form using the following code: $(document).ready ...

Transferring data from a class method to a React component

Situation: In a React component, I have a class with its own methods that is instantiated. What I'm needing: One of the methods in the class changes the value of an input (referred to as `this.$el`) using `.val()`. However, I need to pass this value ...

Tips for implementing a waiting period during an ajax request using jQuery

My current task involves calling a URL to generate a token and then opening another page on the same site once the token is generated. The issue I'm facing is that the window generating the token closes quickly, making it difficult for me to authentic ...

Organizing AngularJS controllers in separate files

I am facing a challenge with my cross-platform enterprise app that is built using Onsen UI and AngularJS. The app has been growing rapidly in size, making it confusing and difficult to manage. Until now, I have kept all the controllers in one app.js file a ...

Script and Ajax loading repeatedly, causing multiple instances of script and Ajax loading

I recently encountered some unexpected issues while debugging and playing around with the code on my website, . Let me walk you through the scenario to understand the problem better. When you click on the "art" tab, two logs appear in the console - one sho ...

Ensure that a child container automatically adjusts its width to fit within a parent container of varying width

There is a wrapping container that contains three floated containers inside. The width of the wrapping container is variable. The inner container on the left has a width of 100px, and the inner container on the right has a width of 500px. The center contai ...

Tips for utilizing the useState Hook in NextJs to manage several dropdown menus efficiently:

Currently, I am in the process of designing an admin panel that includes a sidebar menu. I have successfully implemented a dropdown menu using the useState hook, but it is not functioning exactly as I had envisioned. My goal is to have the if statement onl ...

Update the JSON by replacing any null values with a predefined string

When working with JSON data, I often come across empty values that I need to replace with a default string. var jsonData= [ { "machineNum": "1A", "serialNo": "123", "city": "" }, { "machineNum": "2B", "serialNo": "", "city": "" }, ...

Why are my API routes being triggered during the build process of my NextJS project?

My project includes an API route that fetches data from my DataBase. This particular API route is triggered by a CRON job set up in Vercel. After each build of the project, new data gets added to the database. I suspect this might be due to NextJS pre-exe ...

showing form validation tips alongside form fields

Currently, I have a JavaScript function that effectively displays form validation hints for input elements. However, I am facing an issue with extending this function to work with other form elements such as textarea, select box, and checkboxes. Can anyone ...

Fixed-positioned elements

I'm facing a small issue with HTML5 that I can't seem to figure out. Currently, I have a header image followed by a menu div containing a nav element directly below it. My goal is to make the menu div stay fixed when scrolling down while keeping ...

Running client-side JavaScript code on the server side of an application

Currently, I am in the process of developing a web application that includes a web-based code editor specifically for JavaScript. The main goal of this project is to enable users to run JS code on the client side of the application with the use of server-s ...