When using the ajax method to pass data from the view to the controller, I encountered an issue where the data would unexpectedly become null once it reached the action

function UserLogin() {

    var username = $("#txtUsername").val();
    var passcode = $("#txtPassword").val();
    alert(username);

    $.ajax({

        url: '@Url.Action("Login", "UserAccount")',
        type: "POST",
        data: { 'username': username, 'passcode': passcode },
        datatype: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            alert(data.username);

    }
});

[HttpPost] public ActionResult Login(string username, string passcode) { if (IsValidUser(username, passcode)) { return RedirectToAction("UserInfo", "UserAccount"); } else { ModelState.AddModelError("", "Your Username or password is invalid"); } return View(); }

private bool IsValidUser(string username, string passcode)
{
    string Query = "Select Count(ID) from Users where Username =" + username + " and PassCode = "+ passcode +"";
    int count = Convert.ToInt32(NpgSQLHelper.ExecuteScalar(Utility._connectionstring, System.Data.CommandType.Text, Query));
    if (count > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Answer №1

Deleting the

contentType: "application/json; charset=utf-8"
or updating the contentType to
contentType:"application/x-www-form-urlencoded"
should solve the issue.

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

Navigating a table list in React using arrow keys without inadvertently scrolling the scrollbar

Currently, I've created a table component that contains a list of items. I've implemented hotkeys using the react-hotkeys package to allow users to navigate through the list using the 'arrow up' and 'arrow down' keys. The issu ...

How can I bind an event for changing innerHTML in Angular 2?

Is there a way to implement something similar to this: <div [innerHTML]="content" (innerHTMLchange)="contentInit()"></div> Currently, I have a variable content that is updated by a service fetching a string from my express server. The content ...

Show categories that consist solely of images

I created a photo gallery with different categories. My goal is to only show the categories that have photos in them. Within my three categories - "new", "old", and "try" - only new and old actually contain images. The issue I'm facing is that all t ...

Encountering an error in a Javascript function: Property 'style' is unreadable because it is undefined

When attempting to run this Javascript function, an error message appears stating, 'Cannot read property 'style' of undefined at showSlides' var slideIndex = 1; showSlides(slideIndex); // Next/previous controls function plusSlides(n) ...

Screening for items that meet specific criteria

Currently, the functions are functioning properly by filtering inventory based on barcode and manufacturer. However, I am looking to enhance it to behave like default angularjs filtering. Specifically, I want it so that if I select manufacturer - LG and ba ...

What could be causing the issue of PHP not receiving this multidimensional array through Ajax?

Having an issue with receiving a multidimensional array in PHP after posting it from JS using Ajax: $.ajax({ type: 'post', url: 'external_submit.php', dataType: "json", data: { edit_rfid_changes_submit ...

What is the best way to save functions that can be utilized in both Vue front-end and Node back-end environments at the same time?

As I dive into the world of Node/Express back-end and Vue.js front-end development, along with server-side rendering, I am faced with the need to create utility functions that can format textual strings. These functions need to be accessible and reusable b ...

I am encountering an issue where the results I am expecting to see are not appearing

I am currently in the process of creating a form that utilizes some event handling functions. Below are the functions responsible for handling events within my form: const [name, setUsername] = useState(""); const [age, setAge] = useState(""); const ...

The HTML textarea is not updating properly when using jQuery's keypress event

I am facing an issue with my forms on a webpage, each containing an html textarea: <textarea name="Comment" class="inputTextArea">Hello World!</textarea> There is a javascript event handler that automatically submits the fo ...

The Twitter search API using RestSharp is malfunctioning and displaying an "unauthorized" error message

I'm currently working on creating a Twitter client using RestSharp for API integration. Everything is running smoothly with authentication and fetching timelines, but I've encountered an issue when trying to search Twitter using a hashtag (#). Th ...

Grant the "User" the ability to modify both images and prices

I'm currently working on an art website for a relative and I am looking to provide them with the ability to log in and easily update the images of their paintings as well as adjust the pricing. Is it possible to enable this functionality? My assumptio ...

Storing multilingual JSON data in AngularJS for faster access

I have successfully implemented a multi-language concept in my application, but I am facing an issue where the language (.json) file is being loaded for every field. As a result, the application takes a longer time to load. My requirement is to load the .j ...

Is it possible to apply the DRY Concept to this React JS code?

https://i.stack.imgur.com/jcEoA.png import React from "react"; import { Chip, Box } from '@mui/material'; const Browse = () => { const [chip, setChip] = React.useState("all" ...

Adjusting form elements with Javascript

I'm looking to refresh my knowledge of JS by allowing users to input their first and last names along with two numbers. Upon clicking the button, I want the text to display as, "Hello Name! Your sum is number!" I've encountered an issue in my co ...

Adjust the button's background hue upon clicking (on a Wix platform)

I need some help with customizing the button "#button5" on my Wix website. Here are the conditions I'd like to apply: Button color should be white by default; When the user is on the "contact" page, the button color should change to red; Once the use ...

Steps to update the package version in package.json file

If I remove a package from my project using the following command: npm uninstall react The entry for this package in the package.json file does not disappear. Then, when I install a different version of this package like so: npm install <a href="/cdn ...

ERROR Error: Uncaught (in promise): ContradictionError: The variable this.products is being incorrectly identified as non-iterable, although it

Seeking a way to extract unique values from a JSON array. The data is fetched through the fetch API, which can be iterated through easily. [please note that the product variable contains sample JSON data, I actually populate it by calling GetAllProducts( ...

Having issues with the crucial npm installation of @babel/plugin-transform-react-jsx

Apologies for the inconvenience, but this is my first post. I encountered an issue during npm start, and received this error message: /Users/hp/Desktop/Wszystkie Projekty/ravenous/src/components/BusinessList/BusinessList.js SyntaxError: C:\Users\ ...

Issue with rendering Backbone subview correctly

Today, I delved into the world of website development using backbone.js. Surprisingly, after a whole morning of trying to crack a puzzling problem, I find myself stuck. Let me focus on the crucial bits of code here. Initially, I have a View named Navigat ...

Svelthree - What is the best way to incorporate edges and lines into a scene?

I'm currently experimenting with adding edges to an object in Svelthree. While I understand how to incorporate a geometry into a scene using mesh, I'm unsure of how to include lines at the edges of the geometry. Referencing the official REPL tu ...