ASP.NET MVC4.0 DropDownListFor 设置默认选项

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<SelectListItem>,string.Empty, new { style = "width:180px" })

不能写成:

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

转载于:https://my.oschina.net/kavensu/blog/307376

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值