ドロップダウンリストの項目が選択されていないという問題があります。SelectListItemsの配列を作成し、正しいものをselected = trueに設定していますが、選択されていません。
コントローラに次のコードがあります。
public ActionResult Edit(int id)
{
var p = _myRepository.FindBy(id);
var vm = new MyViewModel(p) { CategoryTypes = ControllerUtils.GetList(_myTypeRepository, r => r.Name, p.CategoryType.Id) };
return View(vm);
}
ControllerUtilsクラスのGetList関数は次のとおりです。
public static class ControllerUtils
{
public static IEnumerable<SelectListItem> GetList<T>(IIntKeyedRepository<T> list, Func<T, string> getName, int id) where T : BaseModel
{
var items = list.All().ToList();
var itemsList = items.Select(r => new SelectListItem() { Selected = r.Id == id, Text = getName(r), Value = r.Id.ToString() });
return itemsList;
}
}
これが私のビューコードです:
<div class="editor-label">
@Html.LabelFor(model => model.MyObject.CategoryType)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.MyObject.CategoryType, Model.CategoryTypes)
@Html.ValidationMessageFor(model => model.MyObject.CategoryType)
</div>
コントローラコードでデバッグし、SelectListItemオブジェクトの配列にリストすると、2番目の項目が選択されていることがわかります=true。しかし、ビューHTMLを確認すると、どちらの項目も選択されていません。
<select id="CategoryType" name="CategoryType">
<option value="1">Choice 1</option>
<option value="2">Choice 2</option>
</select>
ご覧のとおり、どちらのアイテムにも「selected = "selected」はありません。ここで何が起こっているのかについて何か提案はありますか?