下面是一个示例代码,演示了如何在ASP.NET MVC中设置和获取C# DropDownListFor的值。
public class MyViewModel
{
public List Options { get; set; }
public string SelectedValue { get; set; }
}
public ActionResult Index()
{
MyViewModel model = new MyViewModel();
model.Options = new List()
{
new SelectListItem { Text = "Option 1", Value = "1" },
new SelectListItem { Text = "Option 2", Value = "2" },
new SelectListItem { Text = "Option 3", Value = "3" }
};
model.SelectedValue = "2"; // 设置选中的值
return View(model);
}
@model MyViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.SelectedValue, Model.Options, "Select an option")
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
string selectedValue = model.SelectedValue;
// 处理选中的值
return RedirectToAction("Index");
}
这样,就完成了ASP.NET MVC中C# DropDownListFor的设置和获取值的过程。