为下拉列表选择所选项

Choosing selected item for dropdown list in action

我有一个页面允许用户更改他们的隐私设置:

我正在尝试构建我的代码,以便当用户加载此页面时,他们用来 select 隐私设置的下拉列表会显示他们的当前设置,因此如果他们将食谱隐私设置为"Registered users",每当他们加载隐私设置页面时,我希望它以 "Registered users" selected.

开始

最初我创建了一个名为 PrivacySettings

SelectListItem 实例列表
List<SelectListItem> PrivacySettings = new List<SelectListItem>();

            PrivacySettings.Add(
                new SelectListItem
                {
                    Text="Anybody",
                    Value = "0"
                });
            PrivacySettings.Add(
                new SelectListItem
                {
                    Text = "Registered users",
                    Value = "1"
                });
            PrivacySettings.Add(
                new SelectListItem
                {
                    Text = "Only me",
                    Value = "2"
                });

然后我创建三个单独的 SelectList 实例。这是我将每个列表的 selected 值分配给与用户保存的设置匹配的第一个值的部分。

SelectList RecipePrivacyList = new SelectList(
                PrivacySettings,
                "Value",
                "Text",
                PrivacySettings.First(x => x.Value == LoggedInUser.RecipePrivacy.ToString()));


            SelectList ProfilePrivacyList = new SelectList(
                PrivacySettings,
                "Value",
                "Text",
                PrivacySettings.First(x => x.Value == LoggedInUserProfile.Privacy.ToString()));

            SelectList ListPrivacyList = new SelectList(
                PrivacySettings,
                "Value",
                "Text",
                PrivacySettings.First(x => x.Value == LoggedInUser.ListPrivacy.ToString()));

然后我将每个分配给单独的 ViewData

ViewData["RecipePrivacy"] = RecipePrivacyList;
ViewData["ProfilePrivacy"] = ProfilePrivacyList;
ViewData["ListPrivacy"] = ListPrivacyList;

在我看来,我检索了这些并将它们存储到变量中

var ProfilePrivacy = (SelectList)ViewBag.ProfilePrivacy;
var RecipePrivacy = (SelectList)ViewBag.RecipePrivacy;
var ListPrivacy = (SelectList)ViewBag.ListPrivacy;

最后,我使用 Html.DropDownList() 辅助方法使用上述变量创建列表

@Html.DropDownList("profile-privacy", ProfilePrivacy, new { @class = "profile-privacy" })

加载视图时,无论用户的实际设置如何,第一个值("Anyone" 或值 0)都会被 select 编辑。

你必须这样设置 SelectList 的选中项:

SelectList ListPrivacyList = new SelectList(
PrivacySettings,
"Value",
"Text",
PrivacySettings.First(x => x.Value == LoggedInUser.ListPrivacy.ToString()).Value);