2014-12-01 1 views
1

특정 역할이있는 사용자를 나열하는 강력한 형식의보기 (userController에 바인딩 됨)가 있으며 그 아래에 제출 단추가있는 모든 역할을 포함하는 드롭 다운 목록이 있습니다. . 필요한 것은 해당 사용자에게 새로운 역할을 할당하는 것입니다. ActionResult 메서드는 UserRolesController에 있습니다. ActionImaging 메서드에 대한 단추 클릭시 userId 및 RoleId를 전달할 수 있습니까? UserRolesController에서버튼에 매개 변수를 전달하면 강력한 형식의보기가 다른 컨트롤러에 전달됨

ActionResult 방법 :이 같은

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult AddRole(UserRole userRole, int roleId, int userId) 
    { 
     if (!ModelState.IsValid) return View(userRole); 

     var check = db.UserRoles.Any(x => x.RoleID == roleId && x.UserID == userId); 
     if (check) 
      ViewBag.ResultMessage = "This user already has the role specified !"; 
     else 
      db.UserRoles.Add(userRole); 
     db.SaveChanges(); 
     ViewBag.ResultMessage = "User added to the role succesfully !"; 
     return RedirectToAction("Index"); 
    } 

보기 :

@model IEnumerable<MvcAppCRUD.user> 

@{ 
ViewBag.title = "AssignRole"; 
} 

<h2>Assign Role</h2> 
@if (!Model.Any()) 
{ 
@Html.Label("No Roles assigned for this user") 
} 
else 
{ 
<table> 
    <tr> 
     <th> 
      @Html.DisplayName("Email") 
     </th> 
     <th> 
      @Html.DisplayName("Role Name") 
     </th> 
     <th></th> 
    </tr> 
    @foreach (var item in Model) 
    { 
     <tr> 
      <td> 
       @Html.DisplayFor(modelItem => item.email) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.RoleName) 
      </td> 
      <td> 
       @Html.ActionLink("Delete", "Delete", new {id = item.id}) 
      </td> 
     </tr> 
    } 
</table> 
} 
<hr /> 
    <div class="display-label"> 
     @Html.DisplayName("Add Role") 
</div> 

<div class="display-field"> 
@Html.DropDownList("Roles", (SelectList) ViewBag.Roles) 
</div> 

@using (Html.BeginForm("AddRole", "UserRoles")) 
{ 
<div class="message-success">@ViewBag.ResultMessage</div> 
} 
<p> 
    <input type="submit" value="Assign" /> 
</p> 
<p> 
@Html.ActionLink("Back to List", "Index") 
</p> 

모델 엔티티 :

public partial class UserRole 
{ 
public int ID { get; set; } 
public int UserID { get; set; } 
public int RoleID { get; set; } 
public int Status { get; set; } 

public virtual user Users { get; set; } 
public virtual Role Roles { get; set; } 
} 

public partial class user 
{ 
public user() 
{ 
    Roles = new List<SelectListItem>(); 
} 

public long id { get; set; } 
public string email { get; set; } 
public string password { get; set; } 
public System.DateTime reg_date { get; set; } 
public byte validated { get; set; } 
public virtual ICollection<UserRole> UserRoles { get; set; } 
public int RoleId { get; set; } 
public string RoleName { get; set; } 

public IEnumerable<SelectListItem> Roles { get; set; } 

//public IEnumerable<Role> Roles { get; set; } 
} 

public partial class Role 
{ 
public int ID { get; set; } 
public string RoleName { get; set; } 
public string Desc { get; set; } 
public int Status { get; set; } 
public virtual ICollection<UserRole> UserRoles { get; set; } 
} 

버튼에 아무런 변화가 없습니다 클릭합니다. 모델보기에서 다른보기로 매개 변수로 값을 전달할 수 있습니까?

+0

모델 또는 GET 방법을 표시하지 않았습니다. 당신은'Roles'라는 속성을 포함하고 있습니까? 모델 속성과'ViewBag' 속성에 같은 이름을 부여해서는 안됩니다. –

+0

당신은 또한 모델에 IEnumerable 을 전달합니다. 그러나 한 명의 사용자 만 (하나는?) 다시 전달할 것으로 예상하고, 사용자가 제어 할 수있는 컨트롤이 없으므로 어쨌든 아무 것도 게시하지 않습니다. –

+0

코드를 업데이트했습니다. 예 사용자 모델에서 Roles 속성을 선언했습니다. – naeemmalik

답변

0

코드에 여러 가지 문제가 있습니다. 특히 IEnumerable<user>을 모델에 포함시키지 않거나 양식의 컨트롤을 렌더링하지 않으므로 아무 것도 표시되지 않으며 어떤 경우 든 복합 개체 및 드롭 다운 목록에서 단일 값만 반환하기 때문에 UserRole을 게시 할 수 없습니다. 드롭 다운에 모든 역할을 표시 한 후 다시 게시 할 때 이미 선택되어 있는지 확인합니다.보기를 만들 때 사용자가 아직 갖고 있지 않은 역할 만 포함하면됩니다. 그리고 ViewBag에 메시지를 할당하고 리디렉션하는 것은 무의미합니다. 즉각적으로 손실됩니다.

하면 표시 및 편집 (I은 기존 역할을 표시하는 속성을 제외한 주)

public class UserRoleVM 
{ 
    public int ID { get; set; } // user ID for post back 
    public int Name { get; set; } // user name for display in the view 
    [Display(Name="Select new role")] 
    public int SelectedRole { get; set; } 
    public SelectList RoleList { get; set; } 
} 

컨트롤러 원하는 것을 표현하는 뷰 모델을 작성

public ActionResult AddRole(int ID) 
{ 
    UserRoleVM model = new UserRoleVM(); 
    var user = // Get the user based on the ID 
    model.ID = ID; 
    model.Name = user.?? 
    var roles = // Get all roles and remove those that the user already has 
    model.RoleList = new SelectList(roles, "ID", "RoleName"); 
    return View(model); 
} 

보기

@model UserRoleVM 
@using(Html.BeginForm()) 
{ 
    <h2>@Model.Name</h2> // users name 
    @Html.LabelFor(m => m.SelectedRole) 
    @Html.DropDownListFor(m => m.SelectedRole, Model.RoleList) 
    <input type="submit" value="Add Role" /> 
} 

게시 방법

[HttpPost] 
public ActionResult AddRole(UserRoleVM model) 
{ 
    // model is now populated with the ID of the user and the ID of the selected role 
    // save and redirect 
} 
+0

이것은 매우 도움이되며 모든 것을 아주 분명하게 만들었습니다. 저는 그것을 어플리케이션에 구현할 것입니다. 사용자에게 할당되지 않은 역할을 얻는 방법을 안내해 줄 수 있습니까? 그리고 한 가지 더요,이 Action 메서드를 만들 수있는 곳은 어디입니까? 새 컨트롤러를 만들거나 기존 컨트롤러에 포함시켜야합니까? 감사와 정말로 당신의 도움에 감사드립니다. – naeemmalik

+0

귀하의 앱이 어디에 있어야하는지 말하기가 어렵습니다. 'User'와 관련이 있기 때문에'UserController'에있을 수 있지만, 다시 역할을 추가하고 삭제하기위한'RolesController'를 가질 수 있습니다. 어렵고 빠른 규칙이 없습니다. 일관성을 유지하고 다른 사람들이 코드를 따라갈 수 있도록 논리를 유지해야합니다. –

+0

사용자에게 할당되지 않은 역할을 얻는 경우 먼저 모든 역할을 데이터베이스에서 가져온 다음 이미 사용자에게 할당 된 역할을 제거합니다. [이 답변] (http://stackoverflow.com/questions/27224542/passing-response-from-ajax-call-to-view-in-c-sharp/27225961#27225961)를 사용하여 간단한 linq 표현식을 사용하는 예제를 제공합니다. '. 예외()'를 제외하고는 할 수있는 방법이 많습니다 (OP가 그 문제에서 그랬던 것처럼하지 마십시오!). –

관련 문제