溫馨提示×

MVC中怎么為DropDownListFor設(shè)置選中項(xiàng)

MVC
小億
85
2024-03-02 19:47:22
欄目: 編程語言

在MVC中為DropDownListFor設(shè)置選中項(xiàng),可以在視圖中使用SelectListItem對象來指定選中項(xiàng)的值。具體步驟如下:

  1. 在控制器中準(zhǔn)備數(shù)據(jù)源,比如一個(gè)列表數(shù)據(jù)源或者從數(shù)據(jù)庫中獲取數(shù)據(jù)源。

  2. 在視圖中使用DropDownListFor方法來創(chuàng)建下拉列表,并傳入數(shù)據(jù)源和選中項(xiàng)的值。

示例代碼如下:

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        List<SelectListItem> items = new List<SelectListItem>
        {
            new SelectListItem { Text = "Option 1", Value = "1" },
            new SelectListItem { Text = "Option 2", Value = "2" },
            new SelectListItem { Text = "Option 3", Value = "3" },
        };

        ViewBag.Options = items;

        ViewBag.SelectedOption = "2"; // 設(shè)置選中項(xiàng)的值為2

        return View();
    }
}

視圖:

@Html.DropDownListFor(m => m.SelectedOption, ViewBag.Options as List<SelectListItem>)

在上面的代碼中,我們首先在控制器中準(zhǔn)備了一個(gè)下拉列表數(shù)據(jù)源items,并將其存儲(chǔ)在ViewBag中。然后設(shè)置了選中項(xiàng)的值為"2",最后在視圖中使用DropDownListFor方法來創(chuàng)建下拉列表,并指定選中項(xiàng)的值為"2"。這樣在頁面加載時(shí)就會(huì)默認(rèn)選中第二個(gè)選項(xiàng)。

0