MVC @Html.DropDownList - 默认值

发布于 2024-12-15 10:07:43 字数 523 浏览 3 评论 0原文

我有一个在控制器中创建的列表:

    var PayList = new[] {  
                  new ListEntry { Id = 1, Name = "" },       
                  new ListEntry { Id = 2, Name = "Yes" },         
                  new ListEntry { Id = 3, Name = "No" }          

                };

    ViewBag.PayList = new SelectList(PayList, "Id", "Name",2); 

在视图中我有以下内容:

    @Html.DropDownList("Pay", ViewBag.PayList as SelectList) 

我期望上述内容默认为“是”,但没有发生(请注意,我在 ViewBag.PayList 中传递了 2。

I have a list which I created in the controller:

    var PayList = new[] {  
                  new ListEntry { Id = 1, Name = "" },       
                  new ListEntry { Id = 2, Name = "Yes" },         
                  new ListEntry { Id = 3, Name = "No" }          

                };

    ViewBag.PayList = new SelectList(PayList, "Id", "Name",2); 

In the View I have the following:

    @Html.DropDownList("Pay", ViewBag.PayList as SelectList) 

I was expecting the above to default to Yes but did not happen(Note that I am passing 2 in the ViewBag.PayList.

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

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

发布评论

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

评论(1

书间行客 2024-12-22 10:07:43

代码是健全的,但我认为为了使控制器的范围与您的视图适当地通信,您需要执行以下操作:

@Html.DropDownListFor(model => model.PayList)

实际上......这是一篇好文章:dropdownlist 在 MVC3 Razor 中设置选定值

不要使用 ViewBag...熟悉创建 ViewModel。

The code is sound, but I think in order for the scope of the controller to appropriately communicate with your view, you need to do the:

@Html.DropDownListFor(model => model.PayList)

Actually... here's a good article: dropdownlist set selected value in MVC3 Razor

Don't use the ViewBag... get familiar with creating ViewModels.

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