2016-03-04 63 views
0

我編碼一個MVC 5互聯網應用程序,我有關於一個問題,序列化ViewModel屬性添加到JSON object如何將ViewModels屬性設置爲JSON對象?

下面是一個例子ViewModel

public class TestViewModel 
{ 
    public int id { get; set; } 
    public string name { get; set; } 
    public string exampleValue { get; set; } 
} 

如果我有一個Create View,怎麼能我serializeexampleValue財產是一個JSON object,這樣,當[HttpPost]Create ActionResult收到對象時,exampleValue是一個JSON object

我希望能夠在ViewModelModelState.IsValid代碼執行驗證,然後返回ViewModelView如果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發佈爲JSON object

+0

你可以發佈你通過Ajax發送模板對象的例子嗎? –

回答

0

U可以使用JsonFormatter如JsonMediaTypeFormatter根據您的視圖模型要求反序列化JSON數據(或序列化回JSON)