ASP.NET MVC4.0 DropDownListForデフォルトオプションの設定

2345 ワード

public ActionResult Edit(long id = 0)
        {
            Post post = db.Post.Find(id);
            if (post == null)
            {
                return HttpNotFound();
            }
            ViewBag.content = post.content;
            ViewBag.cates = new SelectList(db.PostCate, "id", "name", post.cate_id);
            ViewBag.updetp = new SelectList(db.Bank, "id", "name", post.updept_id);
            var ds = from d in db.Department
                        where d.updep == post.updept_id
                        select new { d.id, d.name };

            ViewBag.depts = new SelectList(ds, "id", "name", post.dept_id);
            return View("~/Views/Post/Edit.cshtml", post);
        }
<p>

                    <label for="cate_id">  :</label>

                    @Html.DropDownListFor(model=>model.cate_id, ViewBag.cates as IEnumerable<SelectListItem>)

                    @Html.ValidationMessage("cate_id", "       ")

                </p>

                <p>

                    <label for="updetp">  :</label>

                    @Html.DropDownListFor(model=>model.updept_id, ViewBag.updetp as IEnumerable<SelectListItem>, String.Empty, new { style = "width:180px" })

                    @Html.ValidationMessage("updept_id", "     ")

                </p>

                <p>

                    <label for="dept_id">  :</label>

                    @Html.DropDownListFor(model => model.dept_id, ViewBag.depts as IEnumerable<SelectListItem>,string.Empty, new { style = "width:180px" })

            

                    @Html.ValidationMessage("dept_id", "       ")

                </p>

ポイントはViewBagですXXはフィールド名と同じ名前にすることはできません.デフォルト値は設定できません.衝突のせいだと思います.
例:
@Html.DropDownListFor(model => model.dept_id, ViewBag.depts as IEnumerable,string.Empty, new { style = "width:180px"})
次のように書くことはできません.
@Html.DropDownListFor(model => model.dept_id,ViewBag.dept_id ‍as IEnumerable,string.Empty, new { style = "width:180px"})