dropdownlist控件设置默认值_DropDownList如何选择默认值

本文介绍了在ASP.NET MVC中遇到的DropdownList控件设置默认值的问题。当在一个页面上有多个DropdownList并且它们使用相同的Items集合时,如何确保每个DropdownList显示对应的SmallViewModel中的默认ItemId。解决方案是利用EditorTemplate,创建一个`SmallViewModel.cshtml`模板文件,将SelectList作为额外视图数据传递,从而实现正确绑定并显示默认值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have many DropDownLists on page

class BigViewModel

{

public List SmallVM {get;set;}

public List Items {get;set;}

//some other properties

}

class SmallViewModel

{

public string ItemId {get;set;}

//some other properties

}

@for( var i = 0;i

{

@Html.DropdownListFor(m=> m.SmallVM.ItemId, Model.Items)

}

//display other properties

in controller

bigViewModel.Items = List

{

new SelectListItem{Value = "1", Text = "aaa"},

new SelectListItem{Value = "2", Text = "bbb"},

new SelectListItem{Value = "3", Text = "ccc"},

}

bigViewModel.SmallVM = new List

{

new SmallViewModel{ItemId = 3},

new SmallViewModel{ItemId = 2},

}

In controller I set diffrent ItemId for every SmallVM and each DropDownList uses the same Items collection. I want to set default Value from SmallViewModel for each DropDownList. For example in this case there are two DropDownLists first should display default text "ccc" and second "bbb".

Should I put diffrent List for every SmallViewModel and set them Selected property or there is other way?

解决方案

This behavior has been reported as a bug on CodePlex but not yet fixed. Using DropDownListFor() in a for loop does not bind correctly and the first option is always selected despite the value of the property. In order for DropDownListFor() to work correctly when using a collection, you need to use an EditorTemplate for the model.

In /Views/Shared/EditorTemplates/SmallViewModel.cshtml

@model SmallViewModel

@Html.DropdownListFor(m => m.ItemId, (SelectList)ViewData["Items"])

Then in the main view

@model BigViewModel

@using(Html.BeginForm())

{

// Pass the select list to the EditorTemplate as addtionalViewData

@Html.EditorFor(m => m.SmallVM, new { Items = Model.Items })

}

You should now have 2 controls displaying "ccc" and "bbb" respectively.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值