The dictionary of parameters has an empty entry for the 'wantedids' parameter, which is of a non-nullable type 'System.Int32', in the 'System.Web.Mvc.JsonResult' method

The console is showing me an error stating that the parameters dictionary contains a null entry for parameter wantedids. I am trying to pass checked boxes to my controller using an array, so only the admin can check all boxes of tips for a specific user. The admin has more than 5 users. Although I am successfully passing the checked elements in my console, it displays an error message saying Internal server error. Can someone help me understand how to update my database with the checked boxes?

<input type="checkbox" class="cktips" idtips="@item.idtips 
checked="@(item.iduser == ViewBag.iduser ? true : false)"/>

.js var wantedids = [];

$("#btnClick").click(function () {
    $(".cktips").each(function () {
     $(this).prop('checked', true);
     ids.push($(this).val());
    });

    $.ajax({
    url: UrlSettingsDocument.Tips,
    data: { ids: ids},
    type: "POST",
    success: function () {
    alert('successs');
    },
    error: function (xhr, ajaxOptions, thrownError) {
    alert(xhr.status);
    alert(thrownError);
   }
 })
})

This is my Controller.cs file

public JsonResult Statics(bool ids,int iduser,int idtips)
{
    try
        {
            if (ids)
            {
                statics = new statics ();
                st.idtips= idtips;
                Database.statics .Add(st);
                Database.SaveChanges();
            }
        else if (!ids)
        {
            var stdelete= Database.statics.Where(a => a.iduser == iduser &&
            a.idtips== idtips).FirstOrDefault();
            Database.statics.Remove(stdelete);
            Database.SaveChanges();
        }
        if (Request.IsAjaxRequest())
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }
    }
    catch (Exception ex)
    {
        Logger.Error("Error: {0}", ex.ToString());
        return null;
    }

Answer №1

It appears that the IDs you are looking for may need to be of type bool, but you are submitting an array of values. What data type should the IDs be? Perhaps they should be integers. Try defining it as int[] wantedIds

I'm not entirely convinced that val() is the correct jQuery method to use for a checkbox. Are you trying to retrieve the value from idtips?

Are you including data for the other parameters in your AJAX post data block?

Update:

You are only passing one parameter in the post:

data: { wantedIds: wantedIds},

However, your method includes more than one parameter:

Statics(bool wantedIds, int idUser, int idTips)

Where are the others being set, since they cannot be nullable int?? They must be provided unless they are set as route parameters.

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

Is the process.env variable used universally for environmental variables, or is it specifically designed for use in Node.js

Can process.env function as a universal environment variable or is it exclusive to NodeJs? https://nodejs.org/dist/latest-v8.x/docs/api/process.html#process_process_env Instructions on setting it using the node command are provided: $ node -e 'proc ...

There is an error in the syntax near 'C:' and a mistake in the syntax near the word 'with'

The syntax is invalid near 'C:'. Additionally, there is an error near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause, or a change tracking context clause, the previous statement must be termi ...

Issue encountered when trying to retrieve a database variable from a mapReduce operation in MongoDB

Greetings! I am currently developing an application that utilizes a MongoDB database. Within this database, there exists a user collection where all user data is stored. The structure of a document in this collection is as follows: { "_id" : ObjectId( ...

What is the best way to send an array and file in the same AJAX request?

When attempting to send both an image file and an array through my AJAX request to a PHP script, I encountered an issue where either the array or the image file doesn't appear. The problem seems to stem from the specific lines that need to be added to ...

"Return to the top" feature that seamlessly integrates with jQuery's pop-up functionality

Currently, I am facing an issue with a jQuery selectmenu list that opens as a popup due to its length. My goal is to add a "back to top" button at the end of the list. While researching online, I came across this tutorial which seems promising, but unfor ...

Issue: missing proper invocation of `next` after an `await` in a `catch`

I had a simple route that was functioning well until I refactored it using catch. Suddenly, it stopped working and threw an UnhandledPromiseRejectionWarning: router.get('/', async (req, res, next) => { const allEmployees = await employees.fi ...

Best practices for organizing data objects in C# Web API to prevent frontend compatibility problems

Currently, I am working on a project for my C# course where I need to create a To Do app with a backend C# Web API. The main challenge involves allowing multiple users to log in from different devices and have separate lists such as "Work" and "Personal". ...

Extract the data that was returned from the AJAX post function

I am looking to create a condition that is dependent on the data received from an ajax post outside of the post function function post(){ $.post('page.php',$('#form').serialize(), function(data) { if(data !== 'good'){a ...

Navigating through props provided within a setup function in Vuejs using the Composition API

I am facing an issue when trying to pass an object into a child component using props in the Composition API setup function of Vue. Instead of utilizing 'Abe', I want to run a query from firebase based on the displayName property of the user. As ...

Incorporating SQLSRV results into clickable <td> elements: A dynamic approach

As a newcomer to the world of JS/PHP/web development, I'm seeking help with a seemingly simple task. My goal is to make each <td> element in a table clickable, and retrieve the text contained within the clicked <td>. Currently, I have a S ...

Color picker can be utilized as an HTML input element by following these steps

After trying out various color pickers, I was not satisfied with their performance until I stumbled upon Spectrum - The No Hassle jQuery Colorpicker. It perfectly met my requirements. <html> <head> <meta http-equiv="content-type" content="t ...

The javascript file is unable to detect the presence of the other file

I am facing an issue with two JavaScript files I have. The first one contains Vue code, while the other one includes a data array where I created the 'Feed' array. However, when trying to output a simple string from that array, the console throws ...

Determine the Size of an Image File on Internet Explorer

Is there an alternative method? How can I retrieve file size without relying on ActiveX in JavaScript? I have implemented an image uploading feature with a maximum limit of 1 GB in my script. To determine the size of the uploaded image file using Java ...

Updating Vue component with mismatched props

I am looking to optimize the Vue component where data is received in varying structures. Take for example Appointment.vue component: <template> <div> <div v-if="config.data.user.user_id"> {{ config.data.user.user_id ...

encase a function with javascript

let myString = "I am creating a program."; //function to calculate number of letters const letterCount = (str) => str.length; //function to calculate number of words const wordCount = (str) => str.split(" ").length; //function ...

AngularJS application failing to initialize without a module being included

I'm feeling a bit lost when it comes to angularjs and I have a question about why my angularjs app is refusing to bootstrap without creating a module, even though egghead.io and other tutorials seem to suggest otherwise. Here's a snippet of my HT ...

Using React: What is the best method for handling asynchronous requests to fetch a FirebaseToken and subsequently utilizing it in an API request?

My React app is interacting with an API through a Client component. Components can access the Client like this (example in the componentDidMount function of the Home page, where I retrieve a list of the user's items): componentDidMount() { let u ...

Creating a simple bootstrap code for developing plugins in Wordpress

After successfully coding in Brackets with the Theseus plugin on my local machine, I encountered a problem when attempting to transfer my code to a Wordpress installation. The transition from Brackets to Wordpress seems far more complicated than expected. ...

Error: [$injector:unpr] Oh no! The AuthServiceProvider Angular Service seems to be MIA

I am currently working on a small AngularJS project and encountering an issue with my service files not being successfully injected into the controllers. I have double-checked for any syntax errors, but despite trying different variations, the problem pers ...

When scrolling, the c# asp.net page experiences jittering, jumping, or lagging issues during updates

While scrolling through my page, I notice that when the update is triggered by the timer, there is a slight jump or lag in the page/scroll position. I have implemented MaintainScrollPositionOnPostBack and it works well when I am stationary on the page, w ...