JMcCon
JMcCon

Reputation: 467

ASP.NET MVC model binding with dynamic viewmodel

What is the recommended way to handle binding a complex viewmodel? For example, using the objects below:

class PersonViewModel
{
   public string FirstName { get; set; }
   public string LastName { get; set; }

   //I have also tried a generic object instead of dynamic with the same results
   public dynamic PreferredSportsTeam  { get; set; }    
}

class SportsTeamViewModel
{
   public string Name { get; set; }
   public string City { get; set; }
}

class BaseballTeamViewModel : SportsTeamViewModel
{
   public double TeamERA { get; set; }
}

class HockeyTeamViewModel : SportsTeamViewModel
{
   public int TotalSaves { get; set; }
}

I am trying to put either an instance of a BaseballTeamViewModel OR a HockeyTeamViewModel into the "PreferredSportsTeam" property of the PersonViewModel and then pass that PersonViewModel to the Edit View to allow the user to edit all of the fields.

I have successfully used EditorTemplates to display the corresponding View of the object stored in the "PreferredSportsTeam" property. However, when submitting the Edit Form the MVC model binder cannot reconstruct whatever object was stored in the PreferredSportsTeam. It does correctly fill the FirstName and LastName properties but the PreferredSportsTeam property always returns as a generic object that I cannot cast into anything else.

Is there something that I am missing or is it simply not possible with the default MVC model binder? I am aware of custom model binders and think they may be a solution but I am not knowledgeable enough about them to understand how they could be used to fix the problem.

Upvotes: 3

Views: 6273

Answers (1)

SpiderCode
SpiderCode

Reputation: 10122

Below code sample shows how to use dynamic object :

var team = new Team();
team.FirstName = "FirstName";
team.LastName = "LastName";

var baseballTeam = new BaseBallTeam();
baseballTeam.TotalSaves = 100;

team.PreferredSportsTeam = new ExpandoObject();
team.PreferredSportsTeam.BaseBallTeam = baseballTeam;

See This for more detailed explanation.

Upvotes: 2

Related Questions