c# - 将默认值设置为 Html.DropDownListFor

标签 c# asp.net-mvc model-view-controller html.dropdownlistfor

我正在使用 viewbag 在 mvc 中填充下拉列表。 如果页面未使用任何其他值保存,我想为此下拉列表设置一个默认值。 否则所选项目应该是他们选择并保存页面的项目。

这就是我填充我的 viewbag 的方式

ViewBag.ListOfCountries = new SelectList(Db.Countries, "CountryCode", "CountryName");

这是 View :

<%: Html.DropDownListFor(m => m.OfficeAddressCountry, (IEnumerable<SelectListItem>)ViewBag.ListOfCountries, new{@class="required"}) %>

最佳答案

如果你想为下拉列表传递默认值,你可以做的是用默认值传递默认 View 模型/模型

示例:

public ActionResult New()
{
    MyViewModel myViewModel = new MyViewModel ();
    myViewModel.OfficeAddressCountry = default value; 
    //Pass it to the view using the `ActionResult`
    return ActionResult( myViewModel);
}

或者你可以试试这个

 var list = new SelectList(Db.Countries, "CountryCode", "CountryName")
 list.Add(new SelectListItem(){Value = 1,Text = "Deafult Item",Selected = true };)
 ViewBag.ListOfCountries = list;

关于c# - 将默认值设置为 Html.DropDownListFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31261389/

相关文章:

c# - C#中如何获取插入行的ID

c# - 保存到文件路径时访问被拒绝

asp.net-mvc - ASP.Net MVC 中的 Google Checkout

c# - 依赖 HTTPContext 的 MVC 测试操作

mysql - Rails 如何修复表以获取任何 url

c# - 如果文本框的值不是数字,如何为 "Error converting data type varchar to bigint"创建更简单、正确的异常处理程序消息?

c# - 在报表查看器中以编程方式触发导出和打印命令

c# - 如何在 C# 中创建命名的 autoresetevent?

c# - C#发送邮件时如何实现Sender ID?

php - 使用 Symfony 路由的 MVC 路由