I’m building an Asp.net MVC 2 application.
I have an entity called Team that is mapped via public properties to two other entities called Gender and Grade.
public class Team
{
public virtual int Id { get; private set; }
public virtual string CoachesName { get; set; }
public virtual string PrimaryPhone { get; set; }
public virtual string SecondaryPhone { get; set; }
public virtual string EmailAddress { get; set; }
public virtual Grade Grade { get; set; }
public virtual Gender Gender { get; set; }
}
I have a ViewModel that looks like this.
public class TeamFormViewModel
{
public TeamFormViewModel()
{
Team = new Team();
Grade = new SelectList((new Repository<Grade>()).GetList(),"ID", "Name",Team.Grade);
Gender = new SelectList((new Repository<Gender>()).GetList(), "ID", "Name", Team.Gender);
}
public Team Team { get; set; }
public virtual SelectList Grade { get; set; }
public virtual SelectList Gender { get; set; }
}
My form renders as I would expect. When I debug the Create method I see that the Gender and Grade properties are NULL on my Team object.
[HttpPost, Authorize]
public ActionResult Create(Team team)
{
try
{
if (ModelState.IsValid)
{
(new Repository<Team>()).Save(team);
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
What am I doing wrong?
Thanks,
Eric
I recommend that you post and bind back to a view model class rather than your entity class. Create an extension method for your view model class that will return your entity class. Here’s some working code:
And finally, the view: