【问题标题】:MVC4 DropDownListFor - showing correct resultMVC4 DropDownListFor - 显示正确的结果
【发布时间】:2013-05-08 12:42:18
【问题描述】:

我有一个 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>

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

【问题讨论】:

  • 您确定页面加载时Model.category 属性中的内容是下拉列表中的内容吗?
  • 是的,因为我可以在详细信息页面中看到它,我从创建页面的下拉列表中选择它

标签: c# asp.net-mvc asp.net-mvc-4 razor html-helper


【解决方案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)

【讨论】:

  • 我不明白把这段代码放在哪里。 var selection 应该在控制器中,但它没有 model.category(也许你的意思是 author.category)。无论如何,问题是下拉获取 SelectList 类型而不是 List 类型...
  • @AlexandraOrlov 将该代码放入您的控制器中,是的,您是对的,对不起,我已将其更改为 author。检查我的编辑,我也为你的视图添加了剃刀代码。
  • 您在视图中写的行的问题是它需要转换为特定类型。它不能被强制转换为 (List)
  • @AlexandraOrlov 这是使用ViewBag 的问题。检查我的更新,我已经为你把它全部放在一个模型中:)
  • 好的,现在完全不同了:) 在我有字符串类别之前。我去看看,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-21
相关资源
最近更新 更多