KKDev
KKDev

Reputation: 160

How to show nested data from viewbag in MVC Razor view

I want to implement Parent-Child Structure in MVC

Like This i get both list from viewBag so how to got nested structure in mvc Razor view my html code here

  <table>
  @{  IEnumerable<SelectListItem> client = ViewBag.Client;
   foreach (var clientobj in client)
    {
     <tr>
       <th><label>@clientobj.Text</label></th>
          <td>
          <table class="list">
            @{                                                                IEnumerable<SelectListItem> project = ViewBag.Project;
            foreach (var projectobj in project)
          {
        <tr>
        <th><label>@projectobj.Text</label></th>
               <td>
          @Html.CheckBox("chk", projectobj.Selected, new { value = projectobj.Value })
              </td>
             </tr>
               }
           }
    </table>
        </td>

         </tr>}
            }

         </table>

my View Model is

public class ClientProjectViewModel
    {
        public int Clientid { get; set; }
        public string ClientName { get; set; }        
        public IEnumerable<ProjectViewModel> project { get; set; }
    }

Upvotes: 0

Views: 942

Answers (1)

Shyju
Shyju

Reputation: 218832

Since you have a view model, you might simply consider loading the correct data to a a list of that and use that to pass data to your view (instead of using ViewBag to pass data)

public ActionResult Details(int id)
{
  var clientList =new List<ClientProjectViewModel> 
  //load clients and it's projects
  clientList.Add(new ClientProjectViewModel { Clientid=1, ClientName="A", 
                                 projects=new List<ProjectViewModel> {
                               new ProjectViewModel { Id=1, Title="ProjectforThisclien1"}
  };    
  return View(clientList)
}

And in your view, which is strongly typed to a List of ClientProjectViewModel.

@model List<ClientProjectViewModel>
@foreach (var client in Model)
{
  <p>@client.ClientName</p>
  @foreach(var project in client.projects)
  {
    <span>@project.Title</span>
  }
}

I hard coded one client with one project, But you may consider replacing it with data from your db.

Upvotes: 1

Related Questions