I have a post request in .net core. When I call it using AJAX, the method is hit, but all my attribute values are null. There are many examples of fixing this around the web, but I can't seem to find one that works. In fact, I have many POST requests in this project, and they all work fine, yet this one does not which leads me to believe I have something simple that I'm just not seeing.
Here is the simplified AJAX call:
let questionChoiceData = {
'QuestionID':'1',
'ChoiceID':'0',
'SurveyID':'1',
'ResponseText':'Did I work?',
'DeleteFlag': '0'
};
$.ajax({
type: 'POST',
url: '/Create_Edit',
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(questionChoiceData),
success: function (data) {
console.log(data);
},
error: function (request, status, error) {
console.log(error);
}
});
Here is my controller code:
[IgnoreAntiforgeryToken]
[Route("[action]")]
[HttpPost]
public IActionResult Create_Edit([FromBody] Choice_Model v)
{
//Everything below was deleted for brevity sake. Just know that When I set a breakpoint, V shows the model with it's attributes, but no attribute values.
}//Method
Here is my model class:
public class Choice_Model
{
string QuestionID { get; set; }
string ChoiceID { get; set; }
string SurveyID { get; set; }
string ResponseText { get; set; }
string DeleteFlag { get; set; }
}
CodePudding user response:
Here is an alternative way to send your data to your Controller
method:
AJAX
:
let questionChoiceData = {
'QuestionID':'1',
'ChoiceID':'0',
'SurveyID':'1',
'ResponseText':'Did I work?',
'DeleteFlag': '0'
};
var json = {
questionChoiceData: questionChoiceData
};
$.ajax({
type: 'POST',
url: '/Create_Edit',
dataType: 'json',
data: {'json': JSON.stringify(json)},
success: function (data) {
console.log(data);
},
error: function (request, status, error) {
console.log(error);
}
});
Controller
:
using Newtonsoft.Json;
[IgnoreAntiforgeryToken]
[Route("[action]")]
[HttpPost]
public IActionResult Create_Edit(string json)
{
Root rootData = new Root();
Choice_Model choice_model = new Choice_Model();
if(!string.IsNotNullOrEmpty(json))
{
//Get the data here in your model
rootData=JsonConvert.DeserializeObject<Root>(json);
choice_model = rootData.questionChoiceData;
}
}//Method
Model
:
public class Choice_Model
{
string QuestionID { get; set; }
string ChoiceID { get; set; }
string SurveyID { get; set; }
string ResponseText { get; set; }
string DeleteFlag { get; set; }
}
public class Root
{
public string json {get;set;}
public Choice_Model questionChoiceData {get;set;}
}