在 ASP.NET MVC 中,可以通过设置DropDownListForselectedValue属性来指定选中项。

以下是一个示例代码:

// 定义一个视图模型
public class MyViewModel
{
    public int SelectedItem { get; set; }
    public List<SelectListItem> Items { get; set; }
}

// 在控制器中设置选中项
public ActionResult Index()
{
    MyViewModel model = new MyViewModel();

    // 假设有一个名为Items的列表,用于填充DropDownList
    model.Items = new List<SelectListItem>
    {
        new SelectListItem { Value = '1', Text = 'Item 1' },
        new SelectListItem { Value = '2', Text = 'Item 2' },
        new SelectListItem { Value = '3', Text = 'Item 3' }
    };

    // 设置选中项
    model.SelectedItem = 2;

    return View(model);
}

// 在视图中使用DropDownListFor
@model MyViewModel

@Html.DropDownListFor(m => m.SelectedItem, Model.Items)

在上述示例中,我们首先定义了一个名为MyViewModel的视图模型,其中包含一个SelectedValue属性和一个Items属性。SelectedValue属性用于指定选中项的值,Items属性用于填充DropDownList。

然后在控制器的Index方法中,我们创建了一个MyViewModel对象,并设置SelectedValue的值为2。

最后,在视图中使用DropDownListFor方法,并将SelectedValueItems作为参数传递。这样,DropDownList就会根据SelectedValue设置选中项。

请注意,SelectedValue的类型必须与Items列表中的值类型匹配,否则无法正确设置选中项。


原文地址: https://www.cveoy.top/t/topic/pmi4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录