我一直在努力解决这个烦人的问题。我有一个模型、编辑器和控制器:
public class TeamDetails{
public int SeasonId{get;set;}
public TeamDetails()
{
//need SeasonId to be populated already from form here, but it won't yet.
}
public TeamDetails(int seasonId)
: this()
{
//load dropdownlist using seasonId from repository
}
}
//Controller
//get method gets seasonId from querystring.
public ViewResult Create(int seasonId)
{
// calls the parameterized constructor for TeamDetails
// which uses seasonId to populate a dropdownlist from db repo.
var teamDetails = new TeamDetails(seasonId);
}
[HttpPost]
public PartialViewResult Create(TeamDetails model)
{
// no such luxury here to call the parameterized
// Constructor for model. additional logic.
}
//editor
@using (Ajax.BeginForm("Create", "Team", options))
{
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.SeasonId)
//additional fields
}
我需要在 TeamDetails 构造函数被击中时已经填充了隐藏字段中的 SeasonId,因为我在构造函数中需要它。但是,这显然不会发生,因为在 MVC 有机会将 SeasonId 分配给对象之前调用了构造函数。有什么办法可以解决这个问题吗?
谢谢
里兹