2011-10-19 24 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> 

値をハードコードします。今は2つの値しかありませんが、db内のデータに基づいて変更することができます。どのようにしてこのラジオボタンのリストをデータベースから動的に取り込むことができますか?おかげ


は、私はこのように私のコントローラでの登録の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

コントローラでは、データベースから値を取得してモデルまたはビューバックに配置する必要があります。それを微調整/

@{ 
    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> 

(私はテスト/これをコンパイルするために取得していないが、あなたは修正することができるはずです。

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

は、その後、あなたのビューで、あなたはそれらを吐き出すためにループを使用しますあなたのニーズに合ってください。)

+0

私はコントローラのActionResultメソッドを次のように登録しています: –