2014-10-28 56 views
0

如果我問一個新手問題,我很抱歉,但我是新來的asp.net mvc。我如何在控制器中看到檢查了哪些單選按鈕?

所以,我有這樣的觀點:

@model FirstProject.Models.SelectRolesViewModel 
@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

@using (Html.BeginForm("SelectRolesOverall","SelectRoles")) 
{ 
    <table class="table"> 
     <tr> 
      <th>Users</th> 
      <th>Roles</th> 
     </tr> 
     @Html.EditorFor(model=>model.UsersAndRoles) 
     <tr> 
      <td></td> 
      <td> 
       <input type="submit" /> 
      </td> 
     </tr> 
    </table> 
} 

而且EditorTemplate:

@model FirstProject.Models.UserRole 

    <tr> 
     <td>@Model.User.UserName</td> 
     <td> 
      @Html.RadioButtonFor(model => model.Role, "Applicant") Applicant 
      <br/> 
      @Html.RadioButtonFor(model => model.Role, "Professor") Professor 
     </td> 
    </tr> 

我的問題是下一步:如何看什麼單選按鈕都在我的控制器之後被檢查提交按鈕已被按下?我想要有以下邏輯:如果申請人已被選中,那麼userRole是申請人,否則如果教授已被選中,則userrole是教授。我的控制器暫時爲空,因爲我不知道該寫什麼。

回答

1

如果你的操作方法是

public SelectRolesOverall(SelectRolesViewModel model) 

那麼你就可以

IEnumerable<UsersAndRoles> usesAndRoles = model.UsersAndRoles; 

訪問收集和訪問集合中的每個項目

foreach (UserRole userRole in model.UsersAndRoles) 
{ 
    string role = userRole.Role; 
    string name = userRole.UserName; // see note below 
} 

注意您還沒有輸入的屬性UserName所以這個值不會回來後,你可能有麻煩匹配角色給用戶。您可能需要添加@Html.HiddenFor(m => m.UserName)或將<td>@Model.User.UserName</td>更改爲<td>@Html.TextBoxFor(m => m.UserName, new { @readonly = "readonly" })</td>

+0

謝謝,非常感謝!有用 ! – 2014-10-29 07:48:25

0

試試這個

public ActionResult [YourActionName](string role) 
{ 
    switch(role){ 
     case "Applicant": /*your applicant logic*/ 
      break; 
     case "Professor": /*your Professor logic*/ 
      break; 
     /* 
      Other logic here 
     */ 
} 

由你自己
注意更換動作的名稱,參數role應該在你的視圖的單選按鈕的名稱相同,這是爲了讓數據綁定工作