MVC在一个模型中有两个视图

时间:2013-01-04 13:32:26

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-viewmodel

我正在尝试在一个模型中组合两个视图。 但是我不能把它弄得太干净了!

你能帮助我吗?

型号:

 public class Player
{
    public int playerID { get; set; }

    [Required]
    [Display(Name = "Spelernaam:")]
    public String playerName { get; set; }

    [Display(Name = "Team:")]
    public int teamID { get; set; }

    public virtual Team Team { get; set; }

    [Required]
    [Display(Name = "Waarde:")]
    public int playerValue { get; set; }
}

public class Team
{
    public int teamID { get; set; }

    [Required]
    [Display(Name = "Teamnaam:")]
    public String teamName { get; set; }

    [Required]
    [Display(Name = "Teamwaarde:")]
    [Range(0, 100, ErrorMessage = "Waarde moet tussen de 0 en de 100 liggen")]
    public int teamValue { get; set; }

    [Required]
    [Display(Name = "Teambudget:")]
    [Range(0, 100000000, ErrorMessage = "Waarde moet tussen de 0 en de 100000000 liggen")]
    public int teamBudget { get; set; }

    [DefaultValue(0)]
    public int gamePoints { get; set; }

    public virtual ICollection<Player> Player { get; set; }
}

我正在尝试在团队的详细信息页面(脚手架)中获取玩家列表。

我已经尝试制作一个viewmodel,它看起来像这样:

public class PlayersPerTeam
{
        public Team Team { get; set; }
        public Player Player { get; set; }
}

但我认为控制器是问题

控制器:

//
    // GET: /Team/Details/5

    public ActionResult Details(int id = 0)
    {
        Team team = db.Teams.Find(id);
        if (team == null)
        {
            return HttpNotFound();
        }
        return View(team);
    }

我希望你能帮助我! 非常感谢!

错误讯息:

The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Team_B041141ED3453289BD09E3CAC14C091B831E03C09FDA76FF2D783BDDCE179358', but this dictionary requires a model item of type 'HerkansingsOpdracht.Models.PlayersPerTeam'.

1 个答案:

答案 0 :(得分:1)

这里的问题是你要么从控制器传递错误的模型,要么你的视图期望错误的模型类型。

如果它是控制器,那么我相信您需要更改类似于此的代码:

public ActionResult Details(int id = 0)
{
    PlayersPerTeam team = new PlayersPerTeam{Team = db.Teams.Find(id)};
    if (team == null)
    {
        return HttpNotFound();
    }
    return View(team);
}

希望这有帮助。