简体   繁体   中英

Displaying objects returned by controller in view in C# MVC

I'm a beginner in C# MVC, but I'm working on some project.

I've searched through Internet and found no solution matching my question. None of the answears solved my problem. The problem is: how to loop through every project (as you will see in code fragments below) and display them in view.

Project model code:

 public class AddProjectViewModel
    {
        [Required]
        [StringLength(50, ErrorMessage = "Project name length is too long. Maximum lenght is 50 char.")]
        public string ProjectName { get; set; }

        [Required]
        [StringLength(50, ErrorMessage = "Description length is too long. Maximum lenght is 50 char.")]
        public string Description { get; set; }
    }

Project controller code:

public ActionResult Index()
    {
        var loggedUser = _workContext.GetUserId();

        var userProjects = _userProjectsRepository.GetAllEntity().Where(x => x.UserId == loggedUser);

        var model = new Models.ProjectViewModels.ShowUserProjectsViewModel();

        model.Projects = userProjects;

        return View(model);
    }

The idea is: when the page loads up, display every project that logged user can see.

I've tried something like this, but it doesn't work:

@model IEnumerable<CarPooling.Website.Models.ProjectViewModels>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach (var item in Model)
{
    <div>
        <p>@Html.DisplayFor(m=>item)</p>
    </div>
}

Please, be patient with me and thanks for every response.

In your controller you are passing to your View a ShowUserProjectsViewModel object, but then you declare your model as IEnumerable<CarPooling.Website.Models.ProjectViewModels> inside your .cshtml View.

Use the same model type you passed inside your controller, and also remember to use the same properties defined in your ViewModel classes, as shown below:

@model ShowUserProjectsViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach (var item in Model.Projects)
{
    <div>
        <p>@Html.DisplayFor(m=>item.ProjectName)</p>
    </div>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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