이 json 문자열을 C# 객체로 비 직렬화하는 데 문제가 있습니다. 모델의 수많은 다른 구성을 시도하고 코드를 serialize하고 mvc 값 공급자가이 작업을 수행 할 수 있지만 작동하도록 가져올 수 없다 ..... 그래서이 JSON 문자열을 보내고 내 컨트롤러로 가져 와서 개체에 넣은 다음 올바른 개체를 만들어 내 데이터베이스에 던져 넣으십시오.값은 null 일 수 없습니다. 객체 역 직렬화
var data = JSON.stringify({
QuestionTitle: title,
Keywords: key,
Description: desc,
Comments: comments,
QuestionType: type,
choices: {
DisplayText: text,
OrderNumber: order,
is_correct:is_correct
}
});
이것은 컨트롤러 방법 :
public ActionResult CreateSimpleQuestion(string json)
{
SimpleQuestion temp = JsonConvert.DeserializeObject<SimpleQuestion>(json);
Question question = new Question();
question.QuestionTitle = temp.QuestionTitle;
question.QuestionType = temp.QuestionType;
question.Keywords = temp.Keywords;
question.is_counted = true;
question.DateCreated = DateTime.Now;
question.Comments = temp.Comments;
question.QuestionType = "Simple";
db.Questions.Add(question);
db.QuestionChoices.Add(temp.choices.First());
db.SaveChanges();
return RedirectToAction("Index");
}
이이 모델 :
public class SimpleQuestion
{
public int QuestionId { get; set; }
public string QuestionTitle { get; set; }
public DateTime DateCreated { get; set; }
public string QuestionType { get; set; }
public string Keywords { get; set; }
public bool is_counted { get; set; }
public string Description { get; set; }
public string Comments { get; set; }
public List<QuestionChoices> choices { get; set; }
}
[ArgumentNullException: Value cannot be null.
Parameter name: value]
Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) +162
Newtonsoft.Json.JsonConvert.DeserializeObject(String value, JsonSerializerSettings settings) +66
InSight.Controllers.QuestionController.CreateSimpleQuestion(String json) +25
이
내가 내 컨트롤러에 보내기 전에 문자열마지막으로 이것은 실제 문자열입니다.
{"QuestionTitle":"This is the Question Title",
"Keywords":"Blue pony, sharks",
"Description":"This is the description field.",
"Comments":"No comment has been left.",
"choices":{
"DisplayText":"Will it rain tomorrow?",
"OrderNumber":"1","is_correct":false
}
}
솔루션 변경 data
다음에 정의 된 JS :
var data = {
"QuestionTitle": title,
"Keywords": key,
"Description": desc,
"Comments": comments,
"QuestionType": type,
"choices": {
"DisplayText": text,
"OrderNumber": order,
"is_correct":false
}
};
이 JSON'choices'는 ** 단일 객체 **입니다. 반면 C# 객체에서는 ** 객체 목록 **입니다. JSON의 객체 목록은 다음과 같습니다.''choices ": [{obj1}, {obj2}]' – user2674389
문자열 화 함수를 수정하면 어떻게 되나요? 나는 이것이 모델 바인더가 올바르게 작동하지 않는 이유에 대한 실제적인 문제라고 생각합니다. – schumacherj
내 대답을 참조하십시오. 귀하의 JavaScript가 이미 잘못되었습니다. 선택 항목이 하나의 객체이기도합니다 (배열 대신) – user2674389