これが繰り返しの質問である場合は申し訳ありません。関連する質問をスキャンしましたが、明確なものは何も見つかりませんでした。
私は Entity オブジェクトを含む EditModel と、その中の 2 つの 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 ディクショナリを使用した場合の例ははるかに単純ですが、SelectList に直接モデル バインディングを使用しようとしている例はあまり多くありませんでした。
どんな助けでも大歓迎です!
クリス