问题背景:
我有一个两页的MVC 4 Web应用程序。当前,第一页的视图将其数据手动输入到视图中,因为它是静态的,即没有任何内容从与其关联的Controller方法传递给视图,如下所示:
索引控制器方法:
Public ActionResult Index()
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
Index.cshtml视图:
<div class="titleHeader">Welcome To This Test Example</div>
Run Code Online (Sandbox Code Playgroud)
最佳实践:
上面的示例可以使用吗,还是应该在Index控制器上生成ViewModel对象,填充静态数据,然后将其返回给View?如图所示:
使用ViewModel的索引控制器索引方法:
Public ActionResult Index()
{
HomePageVM homepageVM = new HomePageVM
{
WelcomeMessage = "Welcome To This Test Example";
};
return View(homepageVM);
}
Run Code Online (Sandbox Code Playgroud)
Index.cshtml现在绑定到HomePageVM ViewModel:
@model TestPage.Models.HomePageVM
<div class="titleHeader">@Model.WelcomeMessage</div>
Run Code Online (Sandbox Code Playgroud) 问题背景:
我通过 HttpResponseMessage 接收到 JSON 响应,如下所示:
var jsonString= response.Content.ReadAsStringAsync().Result;
Run Code Online (Sandbox Code Playgroud)
这给了我以下简单的转义 JSON 字符串结果:
"\"{\\\"A\\\":\\\"B\\\"}\""
Run Code Online (Sandbox Code Playgroud)
问题:
我正在使用 Newtonsoft 尝试将其反序列化为模型:
SimpleModel simpleModel= JsonConvert.DeserializeObject<SimpleModel>(jsonString);
Run Code Online (Sandbox Code Playgroud)
的类模型SimpleModel:
public class SimpleModel
{
public string A { set; get; }
}
Run Code Online (Sandbox Code Playgroud)
转换给了我以下错误:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Error converting value "{"A":"B"}" to type 'PyeWebClient.Tests.ModelConversionTests+SimpleModel'. Path '', line 1, position 15.
Run Code Online (Sandbox Code Playgroud)
我从任务结果收到的 JSON 是有效的,所以我无法理解导致转换错误的问题是什么,格式化 JSON 字符串以便将其转换为其 C# 模型类型的正确方法是什么?