抱歉,如果这是一个重复的问题,我扫描了相关问题并没有看到任何明显的问题。
我正在使用带有实体对象的 EditModel,以及其中的两个 SelectList。问题是,一旦我到达我的 POST 操作,无论我在浏览器上实际选择什么,两个下拉菜单的 SelectedValues 仍然是我在模型的构造函数中设置的默认值。
我的构造函数为 SelectedValues 设置了一些默认值,但它们只是 0 和 ""(它们不是下拉列表中的有效值)。我感觉问题以某种方式围绕着这个问题,但我会提供更多细节。
这是模型的精简版本:
public class UserAccountModel
{
public UserAccount UserAccountData { get; set; } // Entity from EF
public SelectList Organizations { get; set; }
public SelectList Roles { get; set; }
public UserAccountModel() : this(null)
{
}
public UserAccountModel(UserAccount obj)
{
UserAccountData = (obj == null) ? new UserAccount() : obj;
// default selected value
int orgChildId = (UserAccountData.Organization == null) ? 0 : UserAccountData.Organization.ID;
string roleChildId = (UserAccountData.Role == null) ? "" : UserAccountData.Role.Name;
// go get the drop down options and set up the property binding
using (UserAccountRepository rep = new UserAccountRepository())
{
Organizations = new SelectList(rep.GetOrganizationOptions(), "ID", "ID", orgChildId);
Roles = new SelectList(rep.GetRoleOptions(), "ID", "Name", roleChildId);
}
}
public void UpdateModel()
{
UserAccountData.Organization = Organizations.SelectedValue as Organization;
UserAccountData.Role = Roles.SelectedValue as Role;
}
}
这是视图的下拉列表部分:
<div class="field">
<label for="ID">Organization:</label>
<%= Html.DropDownList("ID", Model.Organizations) %>
</div>
<div class="field">
<label for="Name">Role:</label>
<%= Html.DropDownList("Name", Model.Roles) %>
</div>
我可能在这里做了一些愚蠢而明显的事情。使用 ViewData 字典时,这些示例更加直接,但我找不到太多尝试对 SelectLists 使用直接模型绑定的示例。
任何帮助是极大的赞赏!
克里斯