DropDownList对于列表中的第一个选择不显示/保留 Null

发布于 2024-11-06 21:49:15 字数 530 浏览 2 评论 0原文

我通过 SharpArch 有一个 MVC 应用程序。我认为:

 Html.DropDownListFor(x => x.Location, 
     new SelectList(Model.PossibleLocations, "Id", "Address"), 
     "-- No Location --")

我有两个问题。

  1. 当视图绑定到模型时,下拉列表不会更新。
  2. 除非我尝试顶部的“无位置”,否则选择会正确保留。

我能够通过将 x.Location 更改为 x.Location.Id 来解决第一点,但随后我遇到了其他问题。

我可以找到很多 DropDownList 的示例,但没有显示保存 null 的示例。

任何帮助表示赞赏。

谢谢

更新:

我刚刚升级了 Resharper(一个小更新),并收到提示填写它 DropDownListFor。为什么这会有所不同?它本来足以绑定,但现在根本不起作用。

I have an MVC app via SharpArch. In the view I have:

 Html.DropDownListFor(x => x.Location, 
     new SelectList(Model.PossibleLocations, "Id", "Address"), 
     "-- No Location --")

I have 2 issues.

  1. The Dropdown is not getting updated when the view gets bound to the model.
  2. A selection gets persisted correctly except when I try the top "no location".

I was able to take care of the first point by changing x.Location to x.Location.Id but then I had other issues.

I can find plenty of examples for DropDownList, but none in which saving a null is shown.

Any help is appreciated.

Thanks

UPDATE:

I just upgraded Resharper (a minor update) and am getting prompted to fill it DropDownListFor. Why would that make a difference? It was working enough to bind and now it doesn't work at all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

み零 2024-11-13 21:49:15

在传递给 View 之前,您始终可以将“空”SelectListItem 插入到 PossibleLocations 集合中,并检查该“空”值(0 表示例如)当表单发布时

model.PossibleLocations.Insert(0, 
    new SelectListItem() { Text = "-- No Location --", Value = "0" };

You could always insert the "empty" SelectListItem into your PossibleLocations collection before passing to the View and check for that "empty" value (0 for instance) when the form is posted

model.PossibleLocations.Insert(0, 
    new SelectListItem() { Text = "-- No Location --", Value = "0" };
烟柳画桥 2024-11-13 21:49:15

尝试“展平”您的模型类,以便 LocationId 是您要绑定的实际值(即向您的模型添加“LocationId”属性,并为 x => x.LocationId 创建一个 DropDownList )。

Try "flattening" your model class so that LocationId is the actual value you're binding to (i.e. add a "LocationId" property to your model, and create a DropDownList for x => x.LocationId).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文