我有一个页面,允许用户更改其隐私设置:
我正在尝试构建我的代码,以便当用户加载此页面时,用于选择其隐私设置的下拉列表会显示其当前设置,因此如果他们将其配方隐私设置为“注册用户”,则每当他们加载了隐私设置页面,我希望它从选择“注册用户”开始。
最初,我创建了一个名为SelectListItem
PrivacySettings
个实例列表
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
个实例。以下是我将每个列表的选定值分配给与用户保存设置匹配的第一个值的部分。
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" })
加载视图时,无论用户的实际设置如何,都会选择第一个值(“任意”或值0)。
答案 0 :(得分:1)
你必须设置SelectList
的选定项目,如:
SelectList ListPrivacyList = new SelectList(
PrivacySettings,
"Value",
"Text",
PrivacySettings.First(x => x.Value == LoggedInUser.ListPrivacy.ToString()).Value);