@Html.DropdownListがSelectedを消してしまう
しかも"たまに" (# ゚Д゚)ふぁーーっく!!!
こんな状況
//---model--- public class StayType{ public int id{get;set;} public string name{get;set;} } public class Reserve{ [いろいろ] public ICollection<ReserveItem> items{get;set;} } public class ReserveItem{ [いろいろ] public int stayTypeId{get;set;} } //---controller--- public ActionResult Edit(int id){ ViewBag.StayTypes = entity.StayType.ToList(); return View(); } //---View---- @foreach (item in Model.items){ <table> <tr> <td>@Html.DropdownList("StayType",new SelectList(ViewBag.StayTypes,"id","name"item.StayTypeId),new{}) </td> ... }
これで出力すると、StayTypeId=3にも関わらず
<select class="staytypeselect" name="StayType"><option value="1">1泊2食</option> <option value="2">1泊3食</option> <option value="4">1泊朝食</option> <option value="3">1泊夕食</option> <option value="5">素泊まり</option> </select>
こうなる。(# ゚Д゚)
SelectListをダンプするとValue=3のSelectListItemがSelectedになってる。
(# ゚Д゚) ファック
もういい作る
public static MvcHtmlString GLDropDownList(this HtmlHelper htmlHelper, string name, string id ,IEnumerable<SelectListItem> selectList, object htmlAttributes) { if (id == null) id = name; StringBuilder options = new StringBuilder(); options.Append(string.Concat<string>(selectList.Select(sl => GLRenderListItem(sl)))); TagBuilder tagBuilder = new TagBuilder("select") { InnerHtml = options.ToString() }; tagBuilder.MergeAttributes<string, object>(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); tagBuilder.MergeAttribute("name", name, true); tagBuilder.MergeAttribute("id", id, true); tagBuilder.MergeAttributes<string, object>(htmlHelper.GetUnobtrusiveValidationAttributes(name)); return new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal)); } internal static string GLRenderListItem(SelectListItem item) { TagBuilder tagBuilder = new TagBuilder("option") { InnerHtml = HttpUtility.HtmlEncode(item.Text) }; if (item.Value != null) { tagBuilder.Attributes["value"] = item.Value; } if (item.Selected) { tagBuilder.Attributes["selected"] = "selected"; } return tagBuilder.ToString(TagRenderMode.Normal); }
( ゚Д゚) できた。
しかし不可解な現象だ。かんべんしてよもう。