Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a UserProfile Model & A Tasks Model

My index is currently returning the user profile how can i add the tasks to display in the same view page? I was trying something with the view bag but could not get it to work

Controller

SQL
public ActionResult Index()
{
    UserProfile userprofile = db.UserProfiles.Find((int)Membership.GetUser().ProviderUserKey);
    if (userprofile == null)
    {
        return HttpNotFound();
    }

    return View(userprofile);

}


How can i add the data from the Tasks Model to this controller to show on the Index view as a list of all tasks
Posted

You should create a ViewModel class. For example MyNewViewModel and declare the two List of properties in this class like below
C#
public class MyNewViewModel
{
public MyNewViewModel()
{
UserProfiles=new List<userprofile>();
Tasks =new List<task>();
}
public List<userprofile> UserProfiles{get;set;}
public List<task> Tasks {get;set;}

} 


In the view use the model MyNewViewModel
C#
@model MyNewViewModel
{
}
//iterate userprofiles 
@foreach (var item in Model.UserProfiles) {
}
//iterate Tasks
@foreach (var item in Model.Tasks ) {
}


Hope this helps
 
Share this answer
 
v3
Comments
Adam Jones 25-Sep-13 11:59am    
The only issue here is that the use profile is not a list its a single user profile with multiple tasks assigned to that user
Jameel VM 25-Sep-13 12:05pm    
then declare it as a class. assign values before it return to the view.
You simply need to bind the task model then you can make use of viewdata like this.

SQL
public ActionResult Index()
{
    ViewData["task"]="write code for fetching value from task model";
    UserProfile userprofile = db.UserProfiles.Find((int)Membership.GetUser().ProviderUserKey);
    if (userprofile == null)
    {
        return HttpNotFound();
    }

    return View(userprofile);

}



then in view simply fetch the value from viewdata
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900