我正在以 JSON.Stringify($(“ ourForm”)。serializeArray())发送表单数据(找不到将表单发送到控制器的其他方式)>
那么我该如何使用c#在控制器端逆转此Stringify?
字符串是这样的(视图中有2个问题模块):
“ [{{\” name \“:\” question_string \“,\” value \“:\” \“},{\” name \“:\” A \“,\” value \“:\ “ \”},{\“ name \”:\“ B \”,\“ value \”:\“ \”},{\“ name \”:\“ C \”,\“ value \”:\ “ \”},{\“ name \”:\“ D \”,\“ value \”:\“ \”},{\“ name \”:\“ E \”,\“ value \”:\ “ \”},{\“ name \”:\“ correct_answer \”,\“ value \”:\“ \”},{\“ name \”:\“ question_string \”,\“ value \”:\ “ \”},{\“ name \”:\“ A \”,\“ value \”:\“ \”},{\“ name \”:\“ B \”,\“ value \”:\ “ \”},{\“ name \”:\“ C \”,\“ value \”:\“ \”},{\“ name \”:\“ D \”,\“ value \”:\ “ \”},{\“ name \”:\“ E \”,\“ value \”:\“ \”},{\“ name \”:\“ correct_answer \”,\“ value \”:\ “ \”}]“
ViewModel:
public class Questions
{
[Display(Name ="QUESTION HERE")]
public string question_string { get; set; }
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
public string D { get; set; }
public string E { get; set; }
[Display(Name ="CORRECT ANSWER")]
public string correct_answer { get; set; }
}
答案 0 :(得分:1)
这可以通过Newtonsoft.Json
来实现。创建POCO
进行反序列化是最容易的(尽管如果需要,使用dynamic
类型进行反序列化也很棘手)。
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
// Create model we can deserialize to
public class FormData
{
public string Name { get; set; }
public string Value { get; set; }
public FormData(string name, string val)
{
Name = name;
Value = val;
}
}
public class Program
{
public static void Main()
{
var formData = "[{\"name\":\"question_string\",\"value\":\"\"},{\"name\":\"A\",\"value\":\"\"},{\"name\":\"B\",\"value\":\"\"},{\"name\":\"C\",\"value\":\"\"},{\"name\":\"D\",\"value\":\"\"},{\"name\":\"E\",\"value\":\"\"},{\"name\":\"correct_answer\",\"value\":\"\"},{\"name\":\"question_string\",\"value\":\"\"},{\"name\":\"A\",\"value\":\"\"},{\"name\":\"B\",\"value\":\"\"},{\"name\":\"C\",\"value\":\"\"},{\"name\":\"D\",\"value\":\"\"},{\"name\":\"E\",\"value\":\"\"},{\"name\":\"correct_answer\",\"value\":\"\"}]";
var results = JsonConvert.DeserializeObject<List<FormData>>(formData);
foreach (var datas in results)
{
Console.WriteLine(datas.Name);
}
}
}
/* OUTPUT:
question_string
A
B
C
D
E
correct_answer
question_string
A
B
C
D
E
correct_answer
*/