在ASP.NET MVC中,可以使用以下方法设置DropDownList控件的默认值:
public ActionResult MyAction()
{
// 初始化默认值
ViewBag.DefaultValue = "default value";
return View();
}
@Html.DropDownListFor(m => m.PropertyName, Model.DropDownListItems, new { @class = "form-control", @value = ViewBag.DefaultValue })
public class MyViewModel
{
// 其他属性...
public List DropDownListItems { get; set; }
}
public ActionResult MyAction()
{
// 初始化DropDownList的选项
var dropDownListItems = new List
{
new SelectListItem { Text = "Option 1", Value = "1" },
new SelectListItem { Text = "Option 2", Value = "2" },
new SelectListItem { Text = "Option 3", Value = "3" }
};
// 设置默认值
var defaultValue = "2";
var viewModel = new MyViewModel
{
DropDownListItems = dropDownListItems,
PropertyName = defaultValue
};
return View(viewModel);
}
这样,DropDownList控件的默认值就会被设置为2。