我有一个EDIT视图,强烈输入到包含2个字段的模型: 名称和类别。 名称只是一个字符串,类别是从下拉列表中选择的。
我的控制器:
[HttpGet]
public ActionResult EditAuthor(int id)
{
var db = new AuthorDatacontext();
var Author = db.Authors.Find(id);
ViewBag.category = new SelectList(new[] { "ScienceFiction", "fantasy", "LoveStory", "History" });
return View(Author);
}
我的观点:
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.category)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.category, (SelectList)ViewBag.category)
@Html.ValidationMessageFor(model => model.category)
</div>
现在dropDown列表只显示我可以选择的所有选项,但不显示已经选择的选项。 我怎么能首先显示已经显示的类别?
答案 0 :(得分:1)
我认为可能是因为您没有设置IsSelected
属性。试试这个:
首先,让我们制作一个视图模型,这样我们就可以将下拉列表放在那里:
public class AuthorViewModel
{
public Author Author { get; set; }
public List<SelectListItem> Categories { get; set; }
}
然后在你的控制器方法中,让我们填充你的模型:
[HttpGet]
public ActionResult EditAuthor(int id)
{
var db = new AuthorDatacontext();
var selections = new List<string> { "ScienceFiction", "fantasy", "LoveStory", "History" };
var model = new AuthorViewModel();
model.Author = db.Authors.Find(id);
model.Categories = selections
.Select(s => new SelectListItem
{
Text = s,
Value = s,
Selected = s == model.Author.Category
})
.ToList();
return View(model);
}
然后更改您的视图模型类型:
@model AuthorViewModel
然后你可以这样做:
@Html.DropDownListFor(model => model.Author.Category, Model.Categories)