0

I am developing a little application as exercise to learn MVC and ASP.NET, and I have a problem with the following code:

BTW: Sorry... I studied .NET but not ASP, just Windows Forms and nothing about MVC (as a practical way).

This is my View:

@using (Html.BeginForm("userById", "Home", FormMethod.Post))
{
   @Html.TextBoxFor(model => model.Id)
   @Html.ValidationMessageFor(model => model.Id)
   <button type="submit">Subscribe</button>
}

<h3>Value results</h3>
@Html.TextArea("results", new { rows = 40, columns = 80 })

And I want to fill this TextArea (can be another element) with a Json Data

My controller:

[HttpPost]
    public ActionResult userById()
    {
        string receivedData;

        HttpWebRequest req = (HttpWebRequest)WebRequest
            .Create("http://www.mocky.io/v2/5808862710000087232b75ac");

        req.ContentType = "application/json";
        var response = (HttpWebResponse)req.GetResponse();

        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            receivedData = sr.ReadToEnd();
        }

        var data = JsonConvert.DeserializeObject<RootObject>(receivedData);

        List<User> userList = data.clients.ToList();

        foreach (var item in userList)
        {
            ViewData["results"] = item.Id;
        }

        return View("Index");
    }

My idea is populate the TextArea with the Json data that are stored into the variable called userList, but the foreach loop just fill ONE element. :( Can anybody help me?

Thanks in advance!

3
  • You want to display the full json data in the text area as-is? Commented Apr 29, 2017 at 18:15
  • Yes, well display just a field, as a grid for example. One per line Commented Apr 29, 2017 at 18:18
  • Well if you simply want to show all the json data, then you can remove the foreach loop, avoid the json deserialization and instead ViewData["results"] = receivedData; Commented Apr 29, 2017 at 18:21

2 Answers 2

0

In your solution in the foreach loop you constantly overwrite value in VeiwBag. You can populate it with JSON directly if that's what you want:

ViewData["results"] = JsonConvert.SerializeObject(userList);

If you want to display users you can users collection to ViewBag:

ViewData["results"] = userList;

And then in the view build list of users for example:

<ul>
    @foreach(var user in ViewData["results"])
    {
        <li>@user.Name</li>
    }
</ul>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks by your fast answer, so I need to manipulate the Json Data as Objects and for this I was trying to print the User.Id field using a foreach loop. If I set directly the Json Data to the ViewData["results"] I view all the json. :(
@MadDev, yes, I first thought you want a json in a view. You do need to manipulate objects deserialized from json and use them in foreach loop.
I can manipulate objects without problems, in fact I have a List with objects extracted from the json file, but I can show the fields... In fact the problem is very "easy" I just want to show a List in a component (for example the TextArea), but your solutions doesn't works (at least in my case) ;-) I have errors when I tried to manipulate objects in my view.
0

Finally I solved the problem with the following code, I will pleasant if anybody have some idea about how can improve it.

Controller code:

[HttpPost]
    public ActionResult userById()
    {
        string receivedData;

        HttpWebRequest req = (HttpWebRequest)WebRequest
            .Create("http://www.amisteriousurl.com");

        req.ContentType = "application/json";
        var response = (HttpWebResponse)req.GetResponse();

        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            receivedData = sr.ReadToEnd();
        }

        var data = JsonConvert.DeserializeObject<RootObject>(receivedData);
        List<User> userList = data.clients.ToList();
        ViewData["results"] = getId(userList);

        return View("Index");
    }

private string getId(List<User> list)
    {
        StringBuilder sb = new StringBuilder();
        foreach (var item in list)
        {

            sb.Append(item.Id);
            sb.Append("\n");
        }

        return sb.ToString();
    }

View:

@{
ViewBag.Title = "Home";
}

@model InsuranceWebAPI.Models.User

@using (Html.BeginForm("userById", "Home", FormMethod.Post))
{
   @Html.TextBoxFor(model => model.Id)
   @Html.ValidationMessageFor(model => model.Id)
   <button type="submit">Subscribe</button>
}

<h3>Value results</h3>
@Html.TextArea("results", new { rows = 40, columns = 80 })

Model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace InsuranceWebAPI.Models
{
public class RootObject
{
    public IEnumerable<User> clients { get; set; }
}
public class User
{
    private string email;
    private string id;
    private string name;
    private string role;

    public User()
    {

    }

    public User(string email, string id, string name, string role)
    {
        this.Email = email;
        this.Id = id;
        this.Name = name;
        this.Role = role;
    }

    [Required]
    public string Email { get; set; }
    [Required]
    public string Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Role { get; set; }

}
}

Thanks to everybody!

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.