rahul
rahul

Reputation: 91

Having a difficulty passing value of objects in view asp.net MVC

I have joined two tables(Projects, Task_Distribution) and pass the values to View as viewbag. But I can't access the value in view(such as: @item.Project_Id) and if I write like @item it displays the result like This image

How can I access only the value?

here is my controller code:

  public class TableController : Controller
    {
        // GET: Table
            public ActionResult Table()
        {
            Database_testEntities1 db1 = new Database_testEntities1();
            List<Project> p = new List<Project>();
            List<Task_Distribution> t = new List<Task_Distribution>();
            var query = (from PI in db1.Projects join TI in 
    db1.Task_Distribution on PI.Project_Id equals TI.Project_Id select new { PI.Project_Id, TI.Employee_Id }).ToList();
        ViewBag.table = query;
        return View();
    }
}

And this is my view

@{
    ViewBag.Title = "Table";
}

<h2>Table</h2>
<table>
    @foreach (var item in ViewBag.table)
    {

        <tr>
            <td>
                @item
           </td>
        </tr>

    }

</table>

Can you guys give me a solution, please?

Upvotes: 0

Views: 53

Answers (1)

Shyju
Shyju

Reputation: 218732

See this part of your LINQ expression,

select new { PI.Project_Id, TI.Employee_Id }

You are projecting the result to an anonymous object. So what you have in the ViewBag is a list of these anonymous objects. When you loop through them and executes the code @item, razor will call the ToString method on that which renders the property name and values(which is what you are seeing)

You can create a view model to represent this data and do a projection using that

public class ProjectEmployeeVm
{
  public int ProjectId { set;get;}
  public int EmployeeId { set;get;}
}

Now in your LINQ expression,

select new ProjectEmployeeVm { ProjectId = PI.Project_Id,EmployeeId = TI.Employee_Id }

Now in your view,you can use cast your viewbag item to a list of this view model

@foreach (var item in ViewBag.table as List<ProjectEmployeeVm>)
{
   <p>@item.ProjectId<p>
   <p>@item.EmployeeId <p>
}

Also now since you have a view model, why not use that to transfer data to view instead of using dynamic view bag which is prone to errors.

 var items = (from PI in db1.Projects join TI in 
              db1.Task_Distribution on PI.Project_Id equals TI.Project_Id 
              select new ProjectEmployeeVm { ProjectId = PI.Project_Id,
                                             EmployeeId = TI.Employee_Id 
             }).ToList();
return View(items);

Now in your view,

@model List<ProjectEmployeeVm>
@foreach (var item in Model)
{
   <p>@item.ProjectId<p>
   <p>@item.EmployeeId <p>
}

Upvotes: 2

Related Questions