mvc html.listbox,c# - How to use Html.ListBoxFor with MVC4 - Stack Overflow

本文介绍如何在ASP.NET MVC中通过Controller填充Model的国家列表,并在视图中使用ListBoxFor显示和交互。Controller中创建SelectList对象填充国家数据,视图中利用ListBoxFor绑定并设置样式。

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

you can populate you Model list in you controller action as:

someAction

{

CountryModel objcountrymodel = new CountryModel();

objcountrymodel.CountryList = GetAllCountryList();

return View(objcountrymodel);

}

public SelectList GetAllCountryList()

{

List objcountry = new List();

objcountry.Add(new Country { Id = 1, CountryName = "India" });

objcountry.Add(new Country { Id = 2, CountryName = "USA" });

objcountry.Add(new Country { Id = 3, CountryName = "Pakistan" });

objcountry.Add(new Country { Id = 4, CountryName = "Nepal" });

SelectList objselectlist = new SelectList(objcountry, "Id", "CountryName");

return objselectlist;

}

and in your .cshtml, you may use it as:

@Html.ListBoxFor(m => m.SelectedCountry, new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue), new { @Id = "lstcountry", @style = "width:200px;height:60px;" })

for dealing with lists in view, you need to cast it to SelectList type. and in our example, Country is assumed to be a model for that purpose. (having key and value for selectlist)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值