简体   繁体   English

在MVC中读取JSON格式的数据asp.net视图

[英]Read data in JSON format asp.net View in MVC

I wonder what I'm doing wrong, already tested several tutorials without success, the data comes without the formatting that is in the script, in this example I have in my Controller, 我想知道我做错了什么,已经测试了多个教程,但都没有成功,数据来自的格式没有脚本中的格式,在此示例中,我的控制器中包含该格式,

public JsonResult GetDados()
{
    List<Object> resultado = new List<object>();
    resultado.Add(new
    {
        Nome = "studying Json",
        URL = "https://stackoverflow.com/"
    });
    resultado.Add(new
    {
        Nome = "Json ",
        URL = "https://stackoverflow.com/"
    });
    resultado.Add(new
    {
        Nome = "Mr. Json",
        URL = https://stackoverflow.com/"
    });
    return Json(resultado, JsonRequestBehavior.AllowGet);
}

View : 查看:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.js"></script>
<script>
    $(function () {
        $.ajax({
            dataType: "json",
            type: "GET",
            url: "/Home/GetDados",
            success: function (dados) {
                $(dados).each(function (i) {
                    document.writeln("<p>Nome: " + dados[i].Nome + " | URL: " + dados[i].URL + "</p>")
                });
            }
        });
    });
</script>

The correct display of the result would be: 结果的正确显示为:

Nome: studying Json | Nome:学习Json | Url: https://stackoverflow.com/ 网址: https//stackoverflow.com/

Nome: Json | Nome:杰森| Url: https://stackoverflow.com/ 网址: https//stackoverflow.com/

Nome: Mr. Json | Nome:杰森先生| Url: https://stackoverflow.com/ 网址: https//stackoverflow.com/

I have this result see that in document.writeln script, I'm writing the return json with a 我有这个结果,看到在document.writeln脚本中,我用

, the image the result is not the same. ,图像结果不一样。

在此处输入图片说明

Its because you are calling "GetDados" directly from URL, which is why its not executing your view. 这是因为您直接从URL调用“ GetDados”,这就是为什么它不执行您的视图。

Try this.. 尝试这个..

Controller : 控制器:

public ActionResult Index()
{
    return View();
}

View "index" : 查看“索引”:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.js"></script>
<script>
    $(function () {
        $.ajax({
            dataType: "json",
            type: "GET",
            url: "/Home/GetDados",
            success: function (dados) {
                $(dados).each(function (i) {
                    document.writeln("<p>Nome: " + dados[i].Nome + " | URL: " + dados[i].URL + "</p>")
                });
            }
        });
    });
</script>

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

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