MVC 中 html 下拉列表的 SelectedValue

发布于 2024-09-01 11:42:31 字数 460 浏览 6 评论 0原文

我是 MVC 新手,很抱歉我说得有点厚重。我正在使用 VB,

我试图使用数据库中的数据填充 html 下拉列表,但无论如何,第一个项目总是被选中。

我做错了什么?

这是我的代码 - 在控制器中:

ViewData("MatchTypeList") = New SelectList(_db.GetMatchTypes.ToList(), "MatchTypeID", "MatchTypeName", SelectedValue)

在视图中

<%= Html.DropDownList("MatchType", CType(ViewData("MatchTypeList"), IEnumerable(Of SelectListItem)), "Any", New With {.class = "forminput"})%>

I am new to MVC, so sorry if I am being a bit thick. I am using VB

I am trying to fill an html drop down list using data from a db, but the first item is always selected, no matter what.

What am I doing wrong?

Here is my code - In the controller:

ViewData("MatchTypeList") = New SelectList(_db.GetMatchTypes.ToList(), "MatchTypeID", "MatchTypeName", SelectedValue)

And in the view

<%= Html.DropDownList("MatchType", CType(ViewData("MatchTypeList"), IEnumerable(Of SelectListItem)), "Any", New With {.class = "forminput"})%>

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

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

发布评论

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

评论(1

灼痛 2024-09-08 11:42:31

这是mvc的问题。一种解决方法是将下拉列表的名称更改为除属性名称之外的任何名称。然后,在提交之前将名称更改回属性的真实名称。

一个示例:

<script type="text/javascript">

    $(function () {
        $("form").submit(function () {
            $("select").each(
                function () {
                   $(this).attr("name", $(this).attr("name").replace(/ZZZ/, ''));
            });
        });
    });

</script>

<%= Html.DropDownList("MatchTypeZZZ", CType(ViewData("MatchTypeList"), IEnumerable(Of SelectListItem)), "Any", New With {.class = "forminput"})%>

我将 javascript(它使用 JQuery)放置在我的母版页中,以便应用程序中具有下拉列表的任何表单都可以安全地在其名称后附加 ZZZ,然后在提交时设置回其原始名称。

This is a problem with mvc. One work around would be to change the name of the dropdownlist to anything but the name of the property. Then, before submitting to change the name back to the true name of the property.

An example:

<script type="text/javascript">

    $(function () {
        $("form").submit(function () {
            $("select").each(
                function () {
                   $(this).attr("name", $(this).attr("name").replace(/ZZZ/, ''));
            });
        });
    });

</script>

<%= Html.DropDownList("MatchTypeZZZ", CType(ViewData("MatchTypeList"), IEnumerable(Of SelectListItem)), "Any", New With {.class = "forminput"})%>

I place the javascript (it uses JQuery) in my master page so any form in the app that has a dropdownlist can safely have its name appended with ZZZ and then set back to its original name on submission.

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