Crakenar
Crakenar

Reputation: 95

Ajax using ASP.NET Core

I'm working on a project where I need to send some data to my SQL Server using ASP.NET Core on server side. On Client side I'm using Javascript to run my application that send me an Array of Objects that I need to save. So, I thought that using Ajax to send the Data to my Controller ,and then sending it to my server (using EF), could be a good idea. The problem is that I cannot even send a string like : var x = "first try"; to my Controller because I have this error (400) : Error Parsing XML : element not found. I tried multiple things like removing datatype : 'text' or datatype: 'json' or forcing the MIMETYPE to text.

Here is what I have done :

View :

function save (){
   var jsonStringify = JSON.stringify({value : "yo"});
   $.ajax({
      type : 'POST',
      url : "@Url.Action("saveChart")",
      data : {"jsonData" : jsonStringify},
      datatype : "text"
   });
}

I already tried to change data type,Url. My path for the controler = MyWebsite/HomeController/saveChart.

Controller :

[HttpPost]
public IActionResult  saveChart(string jsonData){
   ChartClass chart = new ChartClass();
   int nbr = _connection.Chart.Count();
   chart.value = "check connection controler";
   chart.id = nbr + 1;
   this._connection.Chart.Add(chart);
   this_connection.SaveChanges();
   return View("Views/Home/Chart.cshtml");
}

I tried to put [FromBody] , still nothing.

Model :

public class ChartClass(){
   [Key]
   public int id {get; set;}

   public string valeur {get; set;}
}

But I can acces to my database and so, to my controller using a html form with asp-action="saveChart" asp-controller="Home"

Upvotes: 0

Views: 106

Answers (1)

Fei Han
Fei Han

Reputation: 27825

The default contentType would be application/x-www-form-urlencoded; charset=UTF-8, to make Ajax request(s) with posted data to your saveChart action method, you can try:

$.ajax({
    type: 'POST',
    url: "@Url.Action("saveChart")",
    data: {
        "jsonData": "yo"
    },
    datatype: "text"

    //... 

Test Result

enter image description here

Upvotes: 1

Related Questions