在1个视图中查看2个模型的结果 [英] View Result from 2 models in 1 view

查看:61
本文介绍了在1个视图中查看2个模型的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UserProfile模型&任务模型



我的索引当前正在返回用户配置文件如何添加要在同一视图页面中显示的任务?我正在尝试查看包但无法让它工作



控制器



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

return 查看(userprofile);

}





如何将任务模型中的数据添加到此控制器以显示在索引上查看所有任务的列表

解决方案

您应该创建一个ViewModel类。例如MyNewViewModel并在此类中声明两个属性List,如下所示

  public   class  MyNewViewModel 
{
public MyNewViewModel()
{
UserProfiles = new 列表< userprofile>();
任务= 列表< task>();
}
public 列表< userprofile> UserProfiles { get ; set ;}
public 列表<任务>任务{获取; 设置;}

}





在视图中使用模型MyNewViewModel

 @ model MyNewViewModel 
{
}
// iterate userprofiles
@foreach( var item in Model.UserProfiles){
}
// 迭代任务
@foreach( var item Model.Tasks){
}





希望这有助于


您只需要绑定任务模型,然后就可以使用这样的viewdata。



  public  ActionResult 索引()
{
ViewData [ task] = 编写代码以从任务模型中获取值;
UserProfile userprofile = db.UserProfiles.Find(( int )Membership.GetUser()。ProviderUserKey);
if (userprofile == null
{
return HttpNotFound();
}

return 查看(userprofile);

}







然后在视图中只需从viewdata中获取值


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

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

解决方案

You should create a ViewModel class. For example MyNewViewModel and declare the two List of properties in this class like below

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

@model MyNewViewModel
{
}
//iterate userprofiles 
@foreach (var item in Model.UserProfiles) {
}
//iterate Tasks
@foreach (var item in Model.Tasks ) {
}



Hope this helps


You simply need to bind the task model then you can make use of viewdata like this.

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


这篇关于在1个视图中查看2个模型的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆