gpt4 book ai didi

asp.net-mvc - MVC DropDownList SelectedValue无法正确显示

转载 作者:行者123 更新时间:2023-12-03 12:03:58 26 4
gpt4 key购买 nike

我尝试搜索,但没有找到解决我问题的方法。我在Razor View 上有一个DropDownList,它不会显示我在SelectList中标记为Selected的项目。这是填充列表的 Controller 代码:

var statuses  = new SelectList(db.OrderStatuses, "ID", "Name", order.Status.ID.ToString());
ViewBag.Statuses = statuses;
return View(vm);

这是查看代码:
<div class="display-label">
Order Status</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)
@Html.ValidationMessageFor(model => model.StatusID)
</div>

我遍历了它,即使在 View 中它具有正确的SelectedValue,但是DDL始终显示列表中的第一项,而不管选择的值如何。谁能指出我做错了什么才能使DDL默认为SelectValue?

最佳答案

SelectList构造函数的最后一个参数(您希望能够传递所选的值id)将被忽略,因为DropDownListFor助手使用您作为第一个参数传递的lambda表达式,并使用特定属性的值。

因此,这是执行此操作的丑陋方式:

模型:

public class MyModel
{
public int StatusID { get; set; }
}

Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
ViewBag.Statuses = statuses;

var model = new MyModel();
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}

View :
@model MyModel
...
@Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)

这是使用真实 View 模型的正确方法:

模型
public class MyModel
{
public int StatusID { get; set; }
public IEnumerable<SelectListItem> Statuses { get; set; }
}

Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
var model = new MyModel();
model.Statuses = statuses;
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}

View :
@model MyModel
...
@Html.DropDownListFor(model => model.StatusID, Model.Statuses)

关于asp.net-mvc - MVC DropDownList SelectedValue无法正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10039006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com