简体   繁体   English

在MVC中作为ActionResult对象返回时,如何在视图上显示json格式的输出?

[英]How to show json format output on view when returned as an ActionResult Object in MVC?

HomeController.cs HomeController.cs

public async Task<ActionResult> TestExample()
{
    IEnumerable<Customer> result = await myClient.For<Customer>().FindEntriesAsync();
    return View(result);
}

which will return me a List of Customer data. 这将向我返回客户数据列表。 I want to show this data in json format on the View. 我想在视图上以json格式显示此数据。

I tried like this: 我这样尝试过:

Index.cshtml Index.cshtml

<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model));
</script>

But I do not have the Model :( 但是我没有Model :(

Probably, you have forgotten to specify the type of your model in your View. 可能您忘记了在视图中指定模型的类型。

You need to have the @model type line in the beginning of your View: 您需要在视图的开头添加@model type行:

@model IEnumerable<Customer> 

<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model));
</script>

Try : 尝试:

IEnumerable<Customer> result = await myClient.For<Customer>().FindEntriesAsync();         
ViewBag.Customers = Newtonsoft.Json.JsonConvert.SerializeObject(result);

And in the view 并认为

var customers = @Html.Raw((string)ViewBag.Customers);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM