我想将每个变量与Web服务分开,单独放入视图页面 有一个示例json字符串,例如我的url resul
{"change":[{"object1": "value1", "object2": "value2", "object3": value3, "object4": value4},{"object1": "value1", "object2": "value2", "object3": value3, "object4": value4}]}
public ActionResult Get_test(){WebClient webclient = new WebClient();
webclient.Headers[HttpRequestHeader.ContentType] = "application/json;charset=utf-8";
string url = "My URL";
webclient.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
webclient.Headers.Add("Request-type", "My Method");
string result = webclient.DownloadString(url);
}
如何在视图中显示对象。我有一个空视图(Get_Test)。
答案 0 :(得分:0)
public ActionResult Get_test(){
WebClient webclient = new WebClient();
webclient.Headers[HttpRequestHeader.ContentType] =
"application/json;charset=utf-8";
string url = "My URL";
webclient.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
webclient.Headers.Add("Request-type", "My Method");
string result = webclient.DownloadString(url);`
List<SampleViewModel>
userList = new List<SampleViewModel>();
JObject jObject = JObject.Parse(result);
JToken jUser = jObject["MyMethod"];
foreach (var item in jUser)
{
SampleViewModel user = new SampleViewModel();
user.object1 = (string)item["object1"];
user.object2 = (string)item["object2"];
user.object3 = (int)item["object3"];
user.object4 = (int)item["object4"];
userList.Add(user);
}
return view(userlist);
}
首先,我使用mt Objects建立一个SampleViewModel。然后在视图页面中有一个foreach
@model IEnumerable<WebApplication.Models.SampleViewModel>
@{ViewBag.Title = "Get_Test";}
<table>
<thead>
<tr>
<th>object1</th>
<th>pobject2</th>
<th>object3</th>
<th>object4</th>
</tr>
</thead>
@foreach (var item in Model)
{
<tbody>
<tr>
<td>@item.object1</td>
<td>@item.object2</td>
<td>@item.object3</td>
<td>@item.pobject4</td>
</tr>
</tbody>
}