DropDownListFor从哪里获取模型?

发布于 2025-01-02 13:10:59 字数 200 浏览 0 评论 0原文

您可以使用创建下拉列表

@Html.DropDownListFor(model => model.SelectedId, model.DropDownItems);

,但是 DropDownListFor 从哪里获取要传递到 model => 的值? model.SelectedId lambda 来自?

You can create a dropdownlist using

@Html.DropDownListFor(model => model.SelectedId, model.DropDownItems);

but where does DropDownListFor get the value to pass into the model => model.SelectedId lambda from?

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

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

发布评论

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

评论(1

逆光下的微笑 2025-01-09 13:10:59

SelectedId 只是模型中字段的整数。

模型是从控制器传入的,

return View(myModel);

并且模型可以在顶部的视图中定义

@model mymodelnamespace.RoomBookingInsert

,因此下拉框的值设置为模型中的 SelectedId 字段。

例如,如果这样可以更好地说明的话,正确的字段名称将是 RoomNo

@Html.DropDownListFor(model => model.RoomNo, model.Rooms);

只要 model.DropDownItems (或在我的示例中的 model.Rooms)包含具有该属性值的项目,它就会将其设置为列表中的选定项目作为默认值。

编辑:

如果您使用的是 viewbag,而不是模型,请改用 DropDownList。 (每个输入都有一个用于模型的 for 扩展)

@Html.DropDownList("RoomNo", 
       new SelectList(ViewBag.Rooms as System.Collections.IEnumerable ?? Enumerable.Empty<SelectListItem>(), "RoomNo", "RoomName"),
       new { @value = @ViewBag.RoomNo})

上面创建了一个 ID 为 RoomNo 的输入表单,

并使用一个 SelectList ,它将如果为空则默认为空。定义显示的值和文本的字段设置在选择列表参数的末尾。

最后一位将默认值设置为@ViewBag.RoomNo 的内容。

您还可以在控制器中创建选择列表,然后只需将下拉选项设置为 viewbag.myselectList 实体。

SelectedId is just the integer of the field in the model.

the model is passed in from the controller using

return View(myModel);

And the model can be defined in the view at the top

@model mymodelnamespace.RoomBookingInsert

So the dropdownbox's value is set as the SelectedId field in your model.

A proper field name for example would be RoomNo if that clarifies it better.

@Html.DropDownListFor(model => model.RoomNo, model.Rooms);

As long as model.DropDownItems (or model.Rooms in my example) Contains a item with the value of that attribute, it will set it as the selected item in the list as default.

Edit:

If you are using viewbag, rather than the model, instead use DropDownList. (each input has a for extension for use with models)

@Html.DropDownList("RoomNo", 
       new SelectList(ViewBag.Rooms as System.Collections.IEnumerable ?? Enumerable.Empty<SelectListItem>(), "RoomNo", "RoomName"),
       new { @value = @ViewBag.RoomNo})

This above, creates an input form with id RoomNo,

and uses a SelectList that will default to empty if null. The fields that defined the values and text shown are set at the end of the select list parameters.

The last bit sets the default value to the contents of @ViewBag.RoomNo.

You can also create the select list in the controller, and then simply set the dropdown options to the viewbag.myselectList entity.

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