【问题标题】:MVC DropDownList selected value not workingMVC DropDownList 所选值不起作用
【发布时间】:2014-11-13 09:45:45
【问题描述】:

我正在使用 MVC 5。

我的 ViewBag 列表为

ViewBag.TitleList = new SelectList((new string[] { "Mr", "Miss", "Ms", "Mrs" }), contact.Title);
//contact.Title has selected value.

然后我尝试将数组转换为SelectListItem ( to no avail)

在视图上看起来像

@Html.DropDownListFor(model => model.Title, ViewBag.TitleList as SelectList, "Select")

我也试过

@Html.DropDownList("Title", ViewBag.TitleList as SelectList, "Select")

列表加载成功,但Selected Value is Not selected。 如何解决这个问题?

更新 罪魁祸首是与我的 model.Title 匹配的 ViewBag.Title。将我的模型属性重命名为其他东西,它工作。啊!

【问题讨论】:

  • 使用@Html.DropDownListFor() 如果model.Title 的值是(比如)“Miss”,那么将选择第二个选项(您不需要SelectList 构造函数中的第二个参数)。检查Title 的值是否与选项值之一完全匹配。
  • 是的,标题中的值与列表中的值匹配
  • 可能是该帖子的副本。 [可能重复][1][1]:stackoverflow.com/questions/5858679/…
  • 感谢您的更新。我花了 30 分钟想知道为什么我的标题下拉列表没有被选中。在今天之前我从来不知道这是一个问题 - 谢谢!

标签: c# asp.net-mvc asp.net-mvc-5 html.dropdownlistfor selectlist


【解决方案1】:

在控制器中设置Title属性的值:

ViewBag.TitleList = new SelectList(new string[] { "Mr", "Miss", "Ms", "Mrs" });
viewModel.Title = "Miss"; // Miss will be selected by default

另一个可能的原因(也是正确的原因,基于下面的 cmets)是 ViewData["Title"] 被另一个值覆盖。将 Title 属性的名称更改为任何其他名称,一切都应该正常工作。

【讨论】:

  • Title 在加载时已经有价值。它是编辑方法的一部分。
  • @Ruchan,那么 Title 的值与这 4 个值之一不匹配(可能检查空白),或者您尝试循环执行此操作
  • @Ruchan,您是否有机会使用Title 作为键设置页面标题:ViewBag.Title = "Edit"?尝试将属性名称更改为任何其他名称。
  • 我也是这么想的,把模型属性名改了试试,还是一样
  • 好吧,最后它最终是 ViewBag.Title ......现在太疯狂了。编辑你的答案,这样我就可以选择它作为正确的答案。
【解决方案2】:

当未指定值(即“Id”)时,DropDownListFor 有时无法正常运行。试试这个:

public class FooModel
{
    public int Id { get; set; }
    public string Text { get; set; }
}

var temp = new FooModel[] 
{
    new FooModel {Id = 1, Text = "Mr"}, new FooModel {Id = 2, Text = "Miss"},
    new FooModel {Id = 3, Text = "Ms"}, new FooModel {Id = 4, Text = "Mrs"}
                       };
ViewBag.TitleList = new SelectList(temp, "Id", "Text", 2);

编辑:其他解决方案

var temp = new []
{
    new SelectListItem {Value = "Mr", Text = "Mr"}, new SelectListItem {Value = "Miss", Text = "Miss"},
    new SelectListItem {Value = "Ms", Text = "Ms"}, new SelectListItem {Value = "Mrs", Text = "Mrs"}
};
ViewBag.TitleList = new SelectList(temp, "Value", "Text", "Miss");

【讨论】:

  • 见伊万,当你自己解决一个问题时,它被称为sololution
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 2014-10-26
  • 2020-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多