How to transfer a user's comment from HTML to a C# model through a list within the MVC framework

I have been attempting various solutions, but none seem to be working. My goal is to create post and comment partial classes for a main page where end users can add comments. Currently, I am using MVC 5 and the page loads posts and previous comments.

However, I am facing an issue with the onclick method on the client side in order to connect to the server side. I have tried using javascript and ajax to send a call to the C# method location, but the button doesn't respond when clicked. The post partial class is nested within the main page. See code below

Post view

@model IEnumerable<MVC_5_Skeleton1.Models.Post>
<ul class="mylist">
@{
    @Html.AntiForgeryToken()
    if (Model.Any())
    {
        foreach (var item in Model)
        {        
            @Html.TextBoxFor(model => item.newComment, "NewComment", htmlAttributes: new { @class = "form-control-inline", placeholder = "Who are you" })
            <button type="button" class="btn btn-success btn-block" onclick="AddToCart(@item.newComment)">Post</button>                              
        }
    }

Javascript

<script type="text/javascript">   
    function AddToCart(comment) {
        $.ajax({
            url: '/Controller/GetTest',
            data: { comment: comment },
        }).done(function () {
        alert('Added');
    });
}</script>

Controller...I have tested both with and without HTTPPOST

[HttpPost]
public ActionResult GetTest(String M)
{
    return M();
}

Answer №1

When working on your ajax implementation, remember to include the following parameter

method: "POST",

Also, make sure to update the (string X) in your controller method to (string description)

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

Tips for incorporating external functions into Vue Component data synchronization:

As someone new to JavaScript, I am trying to incorporate external functions into Vue component data bindings, but I am encountering issues. helper.js function groupArrayOfObjects(list, key) { return blah blah } function parseDate(d) { ret ...

Having trouble with sending an AJAX POST request containing a JavaScript object to an ASP.NET MVC controller

I am having trouble using ajax to send a JavaScript object to an asp.net controller. I keep receiving a 500 internal server error. Here is the code I am using: ***JS CODE*** $.ajax({ type: 'POST', url: '/PackageCtr/A ...

Access error message through ajaxError binding

I've reviewed various similar inquiries on Stack Overflow, but none address the issue I'm encountering. Within my global.js file, this is what I have: $(document).ready(function () { $(document).ajaxSend(function () { ShowLoading(); }); ...

The raycaster fails to detect collision with the .gltf model

When using the raycaster to detect mouse intersection with a cube, everything works perfectly: raycaster.setFromCamera(mouse, camera) const intersects = raycaster.intersectObject(cubeMesh) if(intersects.length > 0) console.log('intersecting ...

What could be the reason for this XSS script not making a request to my server?

Currently diving into the realm of XSS attacks to enhance my knowledge on application security. My goal is to extract the user's cookie from a local website and then transmit it to my local server for testing purposes. I've successfully obtained ...

If the user confirms it with a bootstrap dialog box, they will be redirected to the corresponding links

Firstly, I am not interested in using javascript confirm for this purpose. Please read on. For example, adding an onClick attribute to each link with a function that triggers a system dialog box is not what I want. Instead of the standard system dialog bo ...

The asp:TextBox functionality encounters issues when used within the asp:Placeholder element using C#

I'm attempting to dynamically add TextBoxes controls based on items in my database. Below is the asp:PlaceHolder snippet from my .aspx page: <asp:PlaceHolder ID="PlaceHolderHTML" runat="server"></asp:PlaceHolder> From my C# code, I am ge ...

Utilize the "require" keyword to bring in multiple items instead of using the "import" statement

I'm looking to incorporate Apollo Client into my project using the following syntax. import { ApolloClient, InMemoryCache, ApolloProvider, gql } from '@apollo/client'; However, my project setup only supports the use of the "require" keyword ...

Ways to toggle the sliding of text on and off an image?

After spending some time experimenting with my code, I managed to get it working. Essentially, when a user hovers over an image, text now appears over the image. Since this is a gallery, I had to utilize $(this).children in order to target and display the ...

The error message "Next.js 14 does not recognize res.status as a function"

I'm a newcomer to Next.js and I've been wrestling with an issue all day. Here's my API for checking in MongoDB if a user exists: import {connect} from '../../../../lib/mongodb'; import User from '../../../models/userModel&ap ...

What is the best way to invoke a Service from a Directive in AngularJS?

Every time a user clicks, a directive is triggered to change the icon for adding to their favorite list. View: <div class="col col-33"> <i class="icon ion-ios-heart-outline" favorite="place[0].objectId" on-icon="ion-ios-heart-outline" off-ic ...

The error "localStorage is not defined when using an axios interceptor in NextJS"

Within my root directory, there lies a file named api.js. This particular file is responsible for managing calls to an external API, with a focus on request and response interceptors. One specific use case involves injecting the access_token, leading to th ...

An async function cannot be used as a Constructor

I am in the process of creating a constructor function using JavaScript. This constructor needs to be asynchronous because I am utilizing the Phantom JS module for data scraping. As a result, an asynchronous function must be used to scrape data through Pha ...

Toggle class to a div upon clicking menu item

Seeking assistance with jQuery to develop a video player featuring a sub menu for displaying various content options upon selection. Here is a snapshot of the frontend design: view image Upon clicking on 'video' or 'audio', a distinct ...

Selecting the first li element using JQuery selectors

Can anyone help me with creating an onclick event that triggers when the user clicks on the first list item which is labeled as "Any Date"? I am looking to use jQuery to target this specific element. <ul id="ui-id-1" class="ui-menu ui-widget ui-widge ...

Preserving the raw JSON data within deserialized JSON.NET entities

This is a continuation from a previous query concerning Newtonsoft Object → Get JSON string . Here is a representation of the object I am working with: [JsonConverter(typeof(MessageConverter))] public class Message { public Message(string original) ...

What is the best way to add query parameters to router.push without cluttering the URL?

In my current project, I am using NextJS 13 with TypeScript but not utilizing the app router. I am facing an issue while trying to pass data over router.push to a dynamically routed page in Next.js without compromising the clarity of the URL. router.push({ ...

Check the connection to the database and provide a response indicating whether it is successful or

I thought this question would be easy, but I'm struggling with it. My code is supposed to test the connection to a MySQL database and return true if it successfully connects, or false if it doesn't. I attempted to use jQuery and Ajax for this pur ...

Update the state within a different function in Vue.js

Just starting out with Vue.js and I'm trying to figure out how to update the component's state from a function in another file. I have a basic form with only an input file element. Once the user selects a file, the onChange handler will be trigg ...

Display a modal using jQuery, PHP, and Ajax to verify if a user is

Using a combination of jQuery, PHP, and Ajax, I am able to check if a user is logged in or not. JavaScript: jQuery(document).ready(function() { setInterval(function() { jQuery.ajax({ url: 'chkLoggedin.php', type: 'POST', ...