我正在编写MVC 5
互联网应用程序,我对将ViewModel
属性序列化为JSON object
提出了疑问:
以下是ViewModel
示例:
public class TestViewModel
{
public int id { get; set; }
public string name { get; set; }
public string exampleValue { get; set; }
}
如果我有Create View
,我如何serialize
将exampleValue
属性设为JSON object
,以便在[HttpPost]
{{1}时}收到对象,Create ActionResult
是exampleValue
?
我希望能够使用JSON object
代码对ViewModel
执行验证,然后ModelState.IsValid
返回ViewModel
View
与任何其他ViewModel
函数一样,它不处于有效状态。
我写了以下代码:
[HttpPost]
但是,$.ajax({
type: "POST",
async: true,
url: "https://**url**/Create",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(template),
success: function (data) { },
error: function (data) { }
});
[HttpPost]
甚至没有收到Create ActionResult
。我认为这与ViewModel
。
有人可以帮我正确设置[ValidateAntiForgeryToken]
属性为exampleValue
,以便验证对象,然后返回JSON object
,如果不是有效状态?如果单个属性无法序列化为View
,是否可以使用JSON object
以便将整个ModelBinding
发布为ViewModel
?
答案 0 :(得分:0)
你可以使用JsonFormatter(如JsonMediaTypeFormatter)根据你的视图模型要求反序列化Json数据(或序列化回JSON)