2017-01-19 23 views
0

我正在嘗試更改用戶登錄或註銷時要註冊的註冊表單。這是我的嘗試:爲什麼我選擇的角色每個選區顯示一個字母

if (!Request.IsAuthenticated) 
{ 
    ViewBag.Name = new SelectList(_context.Roles.First(x=> x.Name == "Registered Users").Name); 
} 
else 
{ 
    ViewBag.Name = new SelectList(_context.Roles.ToList(), "Name", "Name"); 
} 

它確實顯示只有一個選擇,但它顯示它這樣。但爲什麼?

enter image description here

+0

我的猜測是'SelectList'的構造函數期望一個集合,'string'基本上是一個'char'集合。嘗試將'_context.Roles ...'東西包裝在一個字符串數組初始值設定項(例如'new string [] {...}')中,看看是否能解決這個問題。 – Abion47

回答

3

您使用的SelectList的構造是

SelectList(IEnumerable) 

,通過使用列表中的指定項目初始化的SelectList類的新實例。

您傳遞字符串作爲參數,所以它會識別爲字符的集合,並顯示每一個選擇一個字母

,你可以嘗試使用:

var name = _context.Roles.First(x=> x.Name == "Registered Users").Name; 
    ViewBag.Name = new SelectList(
     new List<SelectListItem> 
     { 
      new SelectListItem {Text = name , Value = name } 
     } 
    ); 
+1

'新列表'是多餘的,因此 - 噪音。 'new []'更簡潔,因此更易讀(元素的類型可以清楚地看到)。 – BartoszKP

+0

@BartoszKP謝謝,它只是一個例子如何實現它。因爲你已經用'new []':)描述過這種情況 – Marusyk

1

要具有單你想元素列表有:

new SelectList(new[] { _context.Roles.First(x=> x.Name == "Registered Users").Name }); 

因爲SelectList構造函數需要一個IEnumerable,即元素顯示的集合。由於字符串是字符集合,因此它可以工作,但將字符串視爲要顯示的元素集合(即單個字符)。

另請注意,您的LINQ查詢並不合理。如果符合條件的元素存在,結果將始終爲"Registered Users"。否則會拋出異常。所以,你可以簡化這一點:

//a class field perhaps? 
private readonly string RegisteredUsersString = "Registered Users"; 
//... 

if (_context.Roles.Any(x => x.Name == RegisteredUsersString)) 
    ViewBag.Name = new SelectList(new[] { RegisteredUsersString }); 
else 
    // throw? display an error? 
相關問題