I am trying to post data from the front end HTML page to the backend code C# in a MVVM, I will either get a 404 or 400 error while making a lot of testing scenarios (usually the path).
Here is the JavaScript code:
$.ajax({
type: 'POST',
url: 'ReportModel/DepAct',
data: JSON.stringify({ prop1: 'value1', prop2: 'value2' }),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert('Data sent to backend!');
},
error: function (xhr, status, error) {
alert('Data was not sent to backend!');
}
});
And this is the backend:
public ActionResult DepAct(List<DepTB> selectedDep)
{
// Process data as needed
return new JsonResult(new { success = true });
}
I tried changing the path, data type, give different kinds of data in the front end and in the backend I tried to add different methods with different parameters like just a string, list based on a class etc.
Update 1:
Modified the code to return the same data type and tested one of the answers but no luck
Javascript
var selectedDep = [{ prop1: "value1", prop2: "value2" }];
$.ajax({
type: 'POST',
url: '/Report/DepAct',
data: JSON.stringify(selectedDep),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('Data sent to backend!');
},
error: function (xhr, status, error) {
alert('Data was not sent to backend!');
}
});
Someone requested for the class as well
public class DepTB1
{
public string prop1 { get; set; }
public string prop2 { get; set; }
}
Method
public ActionResult DepAct([FromBody] List<DepTB1> selectedDep)
{
// Process data as needed
return new JsonResult(new { success = true });
}
2
Answers
The code is working after adding OnPost in front of the method's name in the class
And using the following kind or URL in the Javascript
Thanks all for trying!
Your controller action parameter expecting list but you are sending single object which mismatched with method signature. Another important issue is you are missing [FromBody] because by default ajax request type is
application/x-www-form-urlencoded
but you are sending json data.Assuming you have following class:
Model:
Modify Ajax code:
Note: This would also be correct
JSON.stringify([{ prop1: "value1", prop2: "value2" }])
Add [FromBody] In Controller:
Output:
Note: You can get more details here in Jquery Official Document
Update:
Based on your shared link and description, it appeared that, you are using razor page. While sending ajax request within razor page it requires addition
XSRF-TOKEN
in header, you could add following code snippet within your ajax request:Include XSRF-TOKEN in header:
You can ignore antiforgery token:
You even can ignore forgery token by using
[IgnoreAntiforgeryToken]
before your razor page as following:Page Model:
Ajax:
Ouput: