英文:
Ajax Not Posting Data to Backend MVVM C#
问题
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 });
}
英文:
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 });
}
答案1
得分: 0
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:
public class DepTB
{
public string prop1 { get; set; }
public string prop2 { get; set; }
}
Modify Ajax code:
var selectedDep = [{ prop1: "value1", prop2: "value2" }];
$.ajax({
type: 'POST',
url: '/ReportModel',
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!');
}
});
Note: This would also be correct JSON.stringify([{ prop1: "value1", prop2: "value2" }])
Add [FromBody] In Controller:
public ActionResult OnPost([FromBody] List<DepTB> selectedDep)
{
// Process data as needed
return new JsonResult(new { success = true });
}
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:
headers: {
RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
}
You can ignore antiforgery token:
You even can ignore forgery token by using [IgnoreAntiforgeryToken]
before your razor page as following:
Page Model:
[IgnoreAntiforgeryToken]
public class ReportModel : PageModel
{
public ActionResult OnPost([FromBody] List<DepTB> selectedDep)
{
// Process data as needed
return new JsonResult(new { success = true });
}
}
Ajax:
$.ajax({
type: 'POST',
url: '/ReportModel',
data: JSON.stringify([{ prop1: "value1", prop2: "value2" }]),
dataType: "json",
contentType: "application/json; charset=utf-8",
headers: {
RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (data) {
alert('Data sent to backend!');
},
error: function (xhr, status, error) {
alert('Data was not sent to backend!');
}
});
Output:
英文:
> 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.
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:
public class DepTB
{
public string prop1 { get; set; }
public string prop2 { get; set; }
}
Modify Ajax code:
var selectedDep = [{ prop1: "value1", prop2: "value2" }];
$.ajax({
type: 'POST',
url: '/ReportModel',
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!');
}
});
Note: This would also be correct JSON.stringify([{ prop1: "value1", prop2: "value2" }])
Add [FromBody] In Controller:
public ActionResult OnPost([FromBody] List<DepTB> selectedDep)
{
// Process data as needed
return new JsonResult(new { success = true });
}
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:
headers: {
RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
}
You can ignore antiforgery token:
You even can ignore forgery token by using [IgnoreAntiforgeryToken]
before your razor page as following:
Page Model:
[IgnoreAntiforgeryToken]
public class ReportModel : PageModel
{
public ActionResult OnPost([FromBody] List<DepTB> selectedDep)
{
// Process data as needed
return new JsonResult(new { success = true });
}
}
Ajax:
$.ajax({
type: 'POST',
url: '/ReportModel',
data: JSON.stringify([{ prop1: "value1", prop2: "value2" }]),
dataType: "json",
contentType: "application/json; charset=utf-8",
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (data) {
alert('Data sent to backend!');
},
error: function (xhr, status, error) {
alert('Data was not sent to backend!');
}
});
Ouput:
答案2
得分: 0
The code is working after adding OnPost in front of the method's name in the class
[ValidateAntiForgeryToken]
public IActionResult OnPostDepAct([FromBody] List<DepTB1> selectedDep)
{
// Process data as needed
return new JsonResult(new { success = true });
}
And using the following kind of URL in the JavaScript
var selectedDep = [{ prop1: "value1", prop2: "value2" }];
$.ajax({
type: 'POST',
url: '/Reports/Report?handler=DepAct',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: selectedDep,
success: function (data) {
alert('Data sent to backend!');
},
error: function (xhr, status, error) {
alert('Data was not sent to backend!');
}
});
Thanks all for trying!
英文:
The code is working after adding OnPost in front of the method's name in the class
[ValidateAntiForgeryToken]
public IActionResult OnPostDepAct([FromBody] List<DepTB1> selectedDep)
{
// Process data as needed
return new JsonResult(new { success = true });
}
And using the following kind or URL in the Javascript
var selectedDep = [{ prop1: "value1", prop2: "value2" }];
$.ajax({
type: 'POST',
url: '/Reports/Report?handler=DepAct',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: selectedDep,
success: function (data) {
alert('Data sent to backend!');
},
error: function (xhr, status, error) {
alert('Data was not sent to backend!');
}
});
Thanks all for trying!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论