How to Pass Parameters to ASP.NET MVC Controller using AJAX

Can anyone help me with this issue?

I keep getting the error message stating: "There is no argument given that corresponds to the required formal parameter 'SSN' of HomeController.GetCICO(string)"

This error seems to be originating from the following code snippet:

public JsonResult GetAllCICO()
    {
        var cicos = GetCICO().ToList();
        var jsonResult = Json(new{data = cicos}, JsonRequestBehavior.AllowGet);
        jsonResult.MaxJsonLength = int.MaxValue;
        return jsonResult;
    }

The problematic method in question is the GetCICO function:

public List<CICO> GetCICO(string SSN)
{
List<CICO> cicos = new List<CICO>();
using (SqlConnection con = new SqlConnection())
{
    con.ConnectionString = str;
    using (SqlCommand cmd = new SqlCommand())
    {
        cmd.Connection = con;
        cmd.CommandTimeout = 180;
        cmd.CommandText = "SELECT * FROM source_ips WHERE ssn_or_tin = '"+SSN+"' ORDER BY dateTrans ASC";
        con.Open();
        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            if (sdr.HasRows)
            {
                while (sdr.Read())
                {
                    CICO cico = new CICO()
                    {
                        ssn_or_tin = sdr["ssn_or_tin"] == DBNull.Value ? (double?)null : Convert.ToDouble(sdr["ssn_or_tin"]),
                        cusid = sdr["cusid"] == DBNull.Value ? (double?)null : Convert.ToDouble(sdr["cusid"]),
                        accountNo = sdr["accountNo"] == DBNull.Value ? (double?)null : Convert.ToDouble(sdr["accountNo"]),
                        dateTrans = sdr["dateTrans"].ToString(),
                        transCode = sdr["transCode"] == DBNull.Value ? (int?)null : Convert.ToInt32(sdr["transCode"]),
                        transdescription_1 = sdr["transdescription_1"].ToString(),
                        amount = sdr["amount"] == DBNull.Value ? (double?)null : Convert.ToDouble(sdr["amount"]),
                        cashin = sdr["cashin"] == DBNull.Value ? (double?)null : Convert.ToDouble(sdr["cashin"]),
                        cashout = sdr["cashout"] == DBNull.Value ? (double?)null : Convert.ToDouble(sdr["cashout"]),
                        source = sdr["source"].ToString()
                    };
                    cicos.Add(cico);
                }
            }
        }
        con.Close();
    }
}
return cicos;
}

In addition, here is a snippet of my JavaScript code for further reference:

var SSNdata = { SSN: $("#SSN").val() };
        $.ajax({
            type: "POST",
            url: "/Home/GetCICO",
            data: SSNdata,
            dataType: "json"
        });

Answer №1

Hey there, I see you're attempting to retrieve data using the URI "/Home/GetAllCICO" with a HttpGet method?

If that's the case, here are some code snippets you can try out:

jQuery

var SSNdata = { SSN: $("#SSN").val() };
    $.ajax({
        type: "GET",
        url: "/Home/GetCICO",
        data: SSNdata,
        dataType: "json"
    });

MVC Controller

public JsonResult GetAllCICO(SSNdata data)
{
    var cicos = GetCICO(data.SSN).ToList();
    var jsonResult = Json(new{data = cicos}, JsonRequestBehavior.AllowGet);
    jsonResult.MaxJsonLength = int.MaxValue;
    return jsonResult;
}

SSNdata class

public class SSNdata
{
     public string SSN{get;set;}
}

Hope this information proves useful to you!

Answer №2

Are you unsure about which method to use for posting? Let me show you one way.

JavaScript:

url: "/Home/GetAllCICO"

C#:

[HttpPost]
public JsonResult GetAllCICO(string SSN)
{
    var cicos = GetCICO(SSN).ToList();
    var jsonResult = Json(new{data = cicos});
    return jsonResult;
}

Answer №3

Sample JavaScript Code ::

                var ssnData="123";
                $.ajax({
                                type: "POST",
                                contentType: "application/json;charset=utf-8",
                                data: JSON.stringify({ 'SSNdata': ssnData }),
                                url: '@Url.Action("GetAllCICO", "Home")',
                                dataType: 'json',
                                success: function (cicos) {
                                    //Response data stored in cicos variable
                                }
                            });
    Controller Section::

            public JsonResult GetAllCICO(string SSNdata)
                    {
                        var json=Json("Your list will be shown here",JsonRequestBehavior.AllowGet);
                        return json;
                    }

Answer №4

It appears that you are calling the incorrect Action in the controller named "GetCICO". You should actually be calling "GetALLCICO" in your URL:

url: "/Home/GetCICO"  this is an incorrect URL 

Your corrected URL should be 

url: "/Home/GetALLCICO"

Your JSON Action should look like this:

    [HttpPost]
    public JsonResult GetAllCICO(string SSN)
    {
        var cicos = GetCICO().ToList();
        var jsonResult = Json(new{data = cicos}, JsonRequestBehavior.AllowGet);
        jsonResult.MaxJsonLength = int.MaxValue;
        return jsonResult;
    }

Since you are passing a parameter 'SSN' in your URL:

var SSNdata = { SSN: $("#SSN").val() };
$.ajax({
        type: "POST",
        contentType: "application/json;charset=utf-8",
        url: "/Home/GetAllCICO",
        data: JSON.stringify(SSNdata),
        dataType: "json"
    });

Based on this information, your controller action should be as follows:

[HttpPost]
public JsonResult GetAllCICO(string SSN)

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

What exactly does the term "Application Domain" refer to within the context of .NET, and why

Similar Question: Understanding AppDomain Exploring the Concept of Application Domain in .NET and its Significance Related Links: Utilizing AppDomain in C# ...

The concept of position() is often mistaken for a function

I am currently developing a slider and have included the code below: $(document).ready(function() { // MAKE SLIDER WIDTH EQUAL TO ALL SLIDES WIDTH var totalWidth = 0; $('.slide').each(function() { totalWidth = totalWi ...

Verifying Angular JS Routing: Ensuring the Current URL Matches the Route, including Dynamic URL Parameters

Just setting this up: app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/asd/:id/:slug',{ templateUrl:'views/home/index.html', controller:'Home', publicAccess:true, se ...

Transform every occurrence of http:// to https:// with the help of jQuery or Javascript

Looking for a way to convert links in src tags to use https://, specifically Youtube iframes. Here is an example: <iframe width='650' height='365' src="http://www.youtube.com/embed/y9kBixgYKzw" frameborder="0" allowfullscreen>< ...

Utilize a button to apply styles to a Span element dynamically generated with JavaScript

I am attempting to spin a span generated using JavaScript when a button is clicked. The class is added to the span, but the spinning effect does not apply. <p>Click the button to create a SPAN element.</p> <button onclick="myFunction ...

The Handsontable popup autocomplete editor is unfortunately truncated by the horizontal scrollbar

I have implemented an autocomplete feature on all columns in my project. However, I am facing an issue where the autocomplete editor gets cut off by the horizontal scrollbar. You can see the problem demonstrated in this jsfiddle link. Here is some code re ...

Displaying information before completing map zoom and pan on Bing AJAX map

When using my Bing Ajax Map app, users are presented with a list of locations to choose from. Upon clicking on a row, the map centers and zooms in on the selected location. However, I've encountered an issue where the info window loads before the map ...

An efficient method for duplicating HTML content with varying values

Creating a webapp using Google Script requires displaying a list of ideas including title, description, initiator, and status. This information is stored in an array called "ideas". In the Index file, there is a table structure: <table> <the ...

Guide to transmitting a variable using the JavaScript formData API

Having trouble getting AJAX file (picture) upload functionality to work because of issues with sending variables via the formData API: Here is the code for formData: var data = new FormData(); data.append('SelectedFile', _file.files[0]); data.a ...

Apply a single CSS bounce animation to a specific div when clicked

I have implemented a CSS map pin with some CSS3 animations. You can check it out here: https://jsfiddle.net/xg7xfzeq/ body { background: #e6e6e6; } .pin { width: 30px; height: 30px; border-radius: 50% 50% 50% 0; background: #00cae9; position ...

Using 'jquery.get' in combination with a servlet is

I need a servlet that can handle GET requests and return a specific string. A simple example of the code is shown below: public class QueryHandler extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) ...

What is the best way to adjust viewport settings for child components, ensuring the container size is set to 100vw/100vh for all children

Within my project, I have connected the react-static repository with the react repository using yarn link. "react": "^16.13.1" "react-static": "^6.0.18" I am importing various components from the react-static reposi ...

Navigational(Probe) Pagination and Csharp MongoDB Interface

I am exploring the option of implementing keyset/seek pagination for my MongoDB results using the C# MongoDB Driver, specifically avoiding offset pagination. In my database, I have a variety of tags with the following structure: { "_id" ...

What steps can be taken to ensure a protractor test fails when a function does not succeed

For debugging my protractor test cases, I have developed helper methods. One of the key functions is waiting for an element to be clickable. To ensure that Protractor has enough time to find and enable the element, I am implementing a loop. However, in cas ...

Formik Fields with unique key properties

When mapping text fields, I follow this structure: { AddVehicleFields.map(({formikRef, ...input}) => ( <> <TextField key={formikRef} helperText={ getIn(formik.touched, formikRef) ? getIn(formik. ...

Dealing with TypeScript issues while implementing Multer in an Express application

import multer, { FileFilterCallback } from "multer"; import sharp from "sharp"; import { NextFunction, Request, Response } from "express"; const multerStorage = multer.memoryStorage(); const multerFilter = ( req: Request, ...

Exploring TypeScript and React Hooks for managing state and handling events

What are the different types of React.js's state and events? In the code snippet provided, I am currently using type: any as a workaround, but it feels like a hack. How can I properly define the types for them? When defining my custom hooks: If I u ...

What is the best way to release an NPM package containing both commonjs and ES6 versions?

My goal is to publish a module on npm, but I've encountered outdated solutions and issues with babel configurations. Despite trying various examples, I still run into problems where the code doesn't work as intended. Ideally, I want to write my ...

What is the best way to use Immer to update Zustand state when incorporating objects that are added through a controlled form using React-Hook-

Having some trouble with integrating Zustand and Immer using React-Hook-Form. My goal is to capture a series of values from a form, store them in a list, and allow for the addition of new objects to that list. In this scenario, the user inputs data for a ...

Purge ASP.NET Temporary Assemblies Without Refreshing IIS Servers

After relocating some code from the App_Code folder, I encountered a typical conflict problem between the newly compiled code in my project and the previously existing temporary assemblies stored in the cache. Although deleting the temporary assemblies i ...