Reputation: 15
Good day everyone!
I'm new in using Vue.JS and I'm having a problem in posting object using axios and all the properties received a null values.
Here's my simple Model:
public class Employees
{
public int Id {get;set;}
public string Firstname {get;set;}
public string Lastname {get;set;}
}
Here's 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>
}
And here's my controller that receives the null info.
[HttpPost]
public async Task<IActionResult> Create(Employees employees)
{
...
}
When I put breakpoint in the Create method, it successfully triggers the break point so it means that from client to back-end, there are connected. But the problem is, when I check the values of employees, they are all null.
Upvotes: 0
Views: 4221
Reputation: 39290
I'm not 100% sure but think this.data is undefined according to the example here. You could try the following:
methods:{
submitInfo(){
axios.post(
"Employees/Create",
{
Firstname: this.Firstname,
Lastname: this.Lastname
}
)
.then(function(response){...})
.catch(function(error){...});
}
}
Or a simpler method according to this documentation:
methods:{
submitInfo(){
axios.post(
"Employees/Create",
this.$data
)
.then(function(response){...})
.catch(function(error){...});
}
}
If that doesn't work for you then you can debug the page by opening the developer console in the browser (press F12) and debug on the line to inspect the value of this
:
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){...});
}
}
Upvotes: 0
Reputation: 387
I had the same problem with always receiving null objects and after banging my head on the table for a few hours, it may be that your Employees class is simply missing an empty constructor for the object to be created.
Add inside of:
public class Employees
{
public Employees()
{
}
public int Id {get;set;}
public string Firstname {get;set;}
public string Lastname {get;set;}
}
Upvotes: 0
Reputation: 1360
I guess there's no error in your javascripts. You just need to use this in your controller
[HttpPost]
public async Task<IActionResult> Create([FromBody]Employees employees)
{
...
}
Just use this code in your post method
[FromBody]
Upvotes: 1