2011-10-19 31 views
4

填充單選按鈕列表在Asp.net MVC 3,我有我的單選按鈕設置是這樣的:ASP.NET MVC 3 - 如何從數據庫

<div class="editor-label"> 
      @Html.LabelFor(m => m.Roles) 
     </div> 
     <div class="editor-field"> 
      @Html.RadioButtonFor(model => model.Roles,false) SuperAdmin 
      @Html.RadioButtonFor(model => model.Roles,false) Admin 
      @Html.ValidationMessageFor(model =>model.Roles)<br/> 
     </div> 

的正常工作,但這需要我硬編碼值。現在我只有兩個值,但它可能會根據我的數據庫中的數據進行更改。我怎樣才能從數據庫動態地填充這個單選按鈕列表?由於


我有我的控制器一註冊的ActionResult方法是這樣的:

public ActionResult Register() 
     { 
      // On load, query AdminRoles table and load all admin roles into the collection based on the 
      // the query which just does an order by 
      AdminRolesQuery arq = new AdminRolesQuery(); 
      AdminRolesCollection myAdminRolesColl = new AdminRolesCollection(); 
      arq.OrderBy(arq.RoleName, EntitySpaces.DynamicQuery.esOrderByDirection.Ascending); 
      myAdminRolesColl.Load(arq); 

      // Store The list of AdminRoles in the ViewBag 
      //ViewBag.RadioAdminRoles = myAdminRolesColl.Select(r => r.RoleName).ToList(); 

      ViewData.Model = myAdminRolesColl.Select(r => r.RoleName).ToList(); 

      return View(); 
     } 

所以ViewData.Model具有AdminRoles的列表。那麼我如何在我的模型中訪問這個列表?

+0

是Model.Roles任何角色項目的集合? – Birey

+0

結帳這個[鏈接](http://stackoverflow.com/questions/11848762/dynamic-radiobutton-in-razor) –

回答

3

在您的控制器中,您將需要從數據庫中獲取值並將它們放入模型或視圖包中。

ViewBag.RadioButtonValues = db.Roles.Select(r => r.RoleDescription).ToList(); 

那麼在你看來,你只需要使用一個循環來將它們吐出:

@{ 
    List<String> rbValues = (List<String>)ViewBag.RadioButtonValues; 
} 

<div class="editor-field">   
    @foreach (String val in rbValues) { 
     @Html.RadioButtonFor(model => model.Roles,false) @val 
    } 
    @Html.ValidationMessageFor(model =>model.Roles)<br/> 
</div> 

(我沒能編譯/測試,但你應該能夠修復/它調整到滿足您的需求。)

+0

我在我的控制器中註冊ActionResult方法是這樣的: –