0

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 | Url: https://stackoverflow.com/

Nome: Json | Url: https://stackoverflow.com/

Nome: Mr. Json | Url: https://stackoverflow.com/

I have this result see that in document.writeln script, I'm writing the return json with a

, the image the result is not the same.

enter image description here

2
  • What formatting are you referring to? And if your wanting to create links, then your dados[i].URL value needs to be in a <a> element Commented Oct 24, 2016 at 3:23
  • 1
    Problem description could use some clarification , it's not very clear. Should not be using document.write after page loads...it will wipe whole page out Commented Oct 24, 2016 at 3:26

1 Answer 1

1

Its because you are calling "GetDados" directly from URL, which is why its not executing your view.

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.