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" > Category:</label> @Html. Dropdownlistfor ( model=>model.cate_id, viewbag.cates as ienumerable<selectlistitem>) @ Html.validationmessage ("cate_id", "Please select announcement type") </p> <p> <label for= "UPDETP" > Branch:</label> @Html. DropDownListFor (model= >model.updept_id, viewbag.updetp as ienumerable<selectlistitem>, string.empty, new { style = "width:180px" &NBSP;}) @Html. Validationmessage ("updept_id", "Please select a branch") </p> < p> <label for= "dept_id" > Organization:</label> @Html. Dropdownlistfor (model => model.dept_id, viewbag.depts as ienumerable<selectlistitem>,string. empty, new { style = "width:180px" &NBSP;}) @Html. Validationmessage ("dept_id", "Please select publisher") </p>
The key point is that viewbag.xx cannot have the same name as the field name. Otherwise, the default value cannot be set. It should be because of the conflict.
For example:
@Html. dropdownlistfor (model = model.dept_id, viewbag.depts as Ienumerable<selectlistitem>,string . Empty, new {style = "width:180px"})
cannot be written as:
@Html. dropdownlistfor (model = model.dept_id,viewbag.dept_id ? As ienumerable<selectlistitem>,string. Empty, new {style = "width:180px"})
ASP. MVC4.0 dropdownlistfor Set default options