Issue with submitting content using Asp.Net Core along with Vue.JS and Axios

Hello there!

I'm a novice when it comes to Vue.JS and I'm facing an issue while trying to post an object using axios, as all the properties are being received as null values.

Let me share my basic Model:

public class Employees
{
    public int Id {get;set;}
    public string Firstname {get;set;}
    public string Lastname {get;set;}
}

Below are my HTML and Vue.js codes for posting:

<div id="app">
    <form>
       <input type="text" v-model="Firstname" />
       <input type="text" v-model="Lastname" />
       <button type="button" @@click="submitInfo"> Submit </button>
       <! -- In Razor, we use @@ instead of single @ in order to use the shorthand code of vue.js for @ -->
    </form>
</div>
<!-- All scripts are imported in the layout page so vue.js and axios.js is already in there -->

@section Scripts{
    <script>
        var app = new Vue({
           el: "#app",
           data:{
              Firstname: "",
              Lastname: ""
           },
           methods:{
              submitInfo(){
                  axios.post("Employees/Create",this.data)
                  .then(function(response){...})
                  .catch(function(error){...});
              }
           }
        });
    </script>
}

Now, let's take a look at my controller that is receiving null information.

[HttpPost]
public async Task<IActionResult> Create(Employees employees)
{
...   
}

When I set a breakpoint in the Create method, it gets triggered successfully, indicating a connection between the client and backend. However, the issue lies in the fact that all the values of 'employees' turn out to be null.

Answer №1

It appears that there are no errors in your JavaScript code. To properly handle the data in your controller, you simply need to include the following:

[HttpPost]
public async Task<IActionResult> Create([FromBody]Employees employees)
{
...   
}

Make sure to implement this code within your post method:

[FromBody]

Answer №2

Struggling with a similar issue of constantly receiving null objects, I finally realized that the root cause could be due to your Employees class lacking an empty constructor for object creation.

To resolve this, make sure to include the following code snippet:

public class Employees
{
    public Employees() 
    { 
    }

    public int Id {get;set;}
    public string Firstname {get;set;}
    public string Lastname {get;set;}
}

Answer №3

It seems like there may be an issue with the data being undefined based on the example found here. One possible solution is to try the following:

methods:{
  submitInfo(){
      axios.post(
        "Employees/Create",
        {
          Firstname: this.Firstname,
          Lastname: this.Lastname
        }
      )
      .then(function(response){...})
      .catch(function(error){...});
  }
}

Alternatively, you can use a simpler approach as outlined in the documentation:

methods:{
  submitInfo(){
      axios.post(
        "Employees/Create",
        this.$data
      )
      .then(function(response){...})
      .catch(function(error){...});
  }
}

If these solutions do not work for you, debugging the page using the developer console in your browser (by pressing F12) could help. You can inspect the value of this by adding a debugger statement in your code:

methods:{
  submitInfo(){
      debugger;//it should break here, use the console to see what this is
      axios.post(
        "Employees/Create",
        this.$data
      )
      .then(function(response){...})
      .catch(function(error){...});
  }
}

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

Ways to implement a package designed for non-framework usage in Vue

Alert This may not be the appropriate place to pose such inquiries, but I am in need of some guidance. It's more about seeking direction rather than a definitive answer as this question seems quite open-ended. Overview I've created a package th ...

Attempting to retrieve the value from `document.all["" + object.getAttribute("EndDate", true) + ""].value;` is ineffective in Firefox

In Firefox, document.all["" + object.getAttribute("EndDate", true) + ""].value; works but not in IE. Is there an alternative method that can work across different browsers? ...

The username index is not defined in the file path C:xampphtdocsAppX1signin.php on line 6

Experiencing some challenges with a php script I recently created. As a beginner in php, I understand that my code may not be optimal. These error messages are displayed when the form is submitted: Notice: Undefined index: username in C:\xampp&bsol ...

What steps should I take to develop an Outlook add-in that displays read receipts for action items in sent emails?

Currently, I am in the process of developing an add-in that will enable me to track email activity using a tool called lead-boxer (). With this add-in, I am able to retrieve detailed information about users who have opened my emails by sending them with an ...

FormView does not have a defined namespace prefix asp - How should I specify my Page Directive?

After creating a basic web page using Microsoft Expression Web 4 with an ASP Connection to a local Access DB, I encountered an error when navigating to the page from another webpage. The browser displayed the following errors: Error: Namespace p ...

Steps for highlighting specific character(s) within a textarea

I am working on a program to search for specific characters within a designated <textarea> element. I want to be able to highlight or color the characters that match the search criteria within the text area. How can I achieve this effect and color th ...

Is there a way to mask all communication with the bot and only display the ultimate outcome in Element Web Messenger?

I've been experimenting with the Matrix Element Web Messenger and came across a bot on GitHub (mautrix/whatsapp) that enables connection to Whatsapp. Rather than the traditional process of creating a room, sending a "login" message, and receiving a QR ...

Jquery's intermittent firing of .ajax within if statement

So, I've inherited a rather messy codebase that I need to modernize. The task involves upgrading from an old version of prototype to the latest jQuery 3.2.1 within a dated website built on php and smarty templates (not exactly my favorite). When a lo ...

What could be causing the Jquery keydown event to only trigger every other key press?

Recently, I have put together a thumbnail gallery that can be navigated using left and right arrows. I have noticed that while the right arrow works smoothly, the left arrow only seems to navigate to the previous thumbnail every other time. Can someone ple ...

Tips for resolving the problem of Google Maps repeatedly appearing when utilizing the Auto-Loading feature

I need help understanding the issue that arose when loading the Google Maps API. "You have included the Google Maps API multiple times on this page. This may cause unexpected errors." This error occurred while attempting to automatically load the API. B ...

Steps for resolving the issue "Error: Module not found 'C:Users odri odejs_paypalsrcindex.js'" in Node.js

As I attempt to launch my Node.js project, I'm running into a module resolution error that reads as follows: PS C:\Users\rodri\nodejs_paypal> npm run dev <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=" ...

Revolutionizing the method of projecting a texture onto a halfsphere in three.js projects

I am currently working on a project in three.js where I am trying to project an image onto the inside of a halfsphere. The half sphere is created using the following code: const geometry = new THREE.SphereGeometry(Component.radius, this.resolution, this.re ...

Encountering a compile error with a Next.js React project that cannot be resolved

Encountered an issue while refreshing my project with the command "npm run dev" and reloading the site locally. The console displays "Compiled /not-found" and the site fails to load completely. In addition, none of the elements animated via framer motion ...

Leveraging the power of conditional statements in an Asp.Net Aspx file

Hello everyone, I have a snippet of asp.net aspx code which is displayed below <asp:Repeater ID="rptrSizes" runat="server"> <HeaderTemplate> <table id="T1" class="table table-hover table-condensed"> ...

How can I retrieve the word that comes after a specific word in discord.js

Currently, I'm attempting to create a bot similar to Dad bot, but I'm struggling with implementing the "Hi __ I'm, Dad" feature. Here's the code snippet that I've put together so far: var imWords = ["i'm", "I&a ...

Attempting to implement a click event in JavaScript/jQuery

I have been working on creating a "for" loop that assigns a function to each day in a calendar. This function, when clicked, should generate a card displaying lesson descriptions for the selected day. However, I am encountering an issue where all the card ...

Issue encountered while validating a dropdown selection within a form using JavaScript

I have a form that includes multiple options for users to choose from. My goal is to prevent users from selecting the same option more than once. I've written some JavaScript code for this purpose, but I'm encountering an issue with the alert mes ...

Is it possible to pre-compile a specific, updated page within an existing pre-compiled .Net Web Site?

Within my various projects, I have a collection of user controls that are reused. These controls are all stored within the web site project. When creating extensions for new clients, I find myself precompiling the entire web site and deploying it (which in ...

Error: 'window not defined' or 'document not defined' encountered while importing a module in Next.js

I'm working on integrating a Wysiwyg editor into my web application. However, I encountered an error when trying to import the editor module. I tried using both react-draft-wysiwyg and react-quill. The former resulted in a "window not defined" error, ...

Setting a default value for the longText field in Laravel

I have come across an issue in Laravel where I am unable to assign a default value to longText or text fields. Specifically, I am dealing with a field called "body" that will likely contain some text or HTML. How can I set a default value for this field ...