1

我有一个强类型的 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>

现在下拉列表只显示我可以选择的所有选项,但不显示已经选择的选项。我怎样才能让它首先显示已经显示的类别?

4

1 回答 1

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)
于 2013-05-08T13:12:27.253 回答