'How to show a list into a view with other info in .NET Core API?

I'm creating an application where a registered user can make and view posts, something like a forum. In the "details" view it should be possible for the user to look at his information and the list of the publications he has made, for that, I have created a model class with two classes, one for the user's data and another to list the publications . To retrieve all the necessary data, the API receives an int, which is the user id, sent from the MVC controller and its respective view, so basically the API is used by a view and its MVC controller.

The problem I have is that the response coming from the API to the MVC controller is the 500 error, because of that (I think), on the foreach of the view the System.NullReferenceException: 'Object reference not set to an instance of an object.' exception happens. I have been looking for the error by putting some breakpoints in the API, but there are no exceptions or anything like that.

The Model:

public class UserForumModel
{
    public User user { get; set; } //user data like name, email, id, etc...
    public IList<Forum> userForum { get; set; } //the list with the posts made by the user
}

The API controller:

    [HttpGet]
    [Route("viewUser/{id}")]
    public IActionResult viewUser(int id)
    {
        UserForumModel userInfo = new UserForumModel();

        var user = db.User.Where(x => x.Id == id).FirstOrDefault();

        var userForum = db.Forum.Where(x => x.IdUser == user.Id).ToList();

        userInfo.user = user;
        userInfo.userForum = userForum;

        return Ok(userInfo);
    }

The MVC controller:

    [HttpGet]
    public async Task<IActionResult> viewUser(int id)
    {
        UserForumModel userInfo = new UserForumModel();

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://localhost:44325/api/Admin/");

            var responseTask = client.GetAsync("viewUser/" + id);

            responseTask.Wait();

            var result = responseTask.Result; //here is where the 500 error can be seen
                                              //with a breakpoint

            if (result.IsSuccessStatusCode)
            {
                var apiResp = await result.Content.ReadAsStringAsync();

                userInfo = JsonConvert.DeserializeObject<UserForumModel>(apiResp);

                return View(userInfo);
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Server error");

                return View();
            }
        }
    }

The View:

@model APIproyect.Models.UserList.UserForumModel

 <div class="main">
 <div>
    <hr />
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.user.Name)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.user.Name)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.user.Email)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.user.Email)
        </dd>
    </dl>
    <table class="table">
        <thead>
            <tr>
                <th>
                    Tittle
                </th>
                <th>
                    Post date
                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.userForo) <!--the exception happens-->
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Tittle)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Postdate)
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

I have been stuck on this for some time, any help is greatly appreciated.

UPDATE

I changed the model; I removed the List part and stored the user data using a variable for each field.

public class UserForumModel
{
    public string Name { get; set; } //user data like name, email, id, etc...
    public string Email {get; set;}

    //public IList<Forum> userForum { get; set; } //the list with the posts made by the user
}

With the above code, the API response returns 200 (Ok). But I still can't come up with a true solution.

Any help is appreciated.



Solution 1:[1]

I managed to solve my problem thanks to the previous answer and comments. This is what I did with the help I received:

On the API controller:

    [HttpGet]
    [Route("viewUser/{id}")]
    public ActionResult<UserForumModel> viewUser(int id)
    {
        var user = db.Users.Where(x => x.Id == id).FirstOrDefault();

        var model = new UserForumModel
        {
            user = new User
            {
                Id = user.Id,
                Name = user.Name,
                Email = user.Email
            },

            userForum = db.Forum.Select(s => new Forum()
                {
                    IdUser = s.IdUser,
                    Tittle = s.Tittle,
                    PostDate = s.PostDate
                }
            ).Where(x=>x.Id == user.Id).ToList<Forum>(),
            
        };

        return Ok(model);
    }

The model:

public class UserForumModel
{
    public Users user { get; set; }
    public IList<Forum> userForum { get; set; }
}

With the above code I made the view show the information and the list.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel