2013-01-18 4 views
2

전 제 질문을 검색했지만 couldnt 더 이상 얻을 수 있도록 아무것도 찾을 수 없습니다.ASP.NET MVC : 컨트롤러에 복잡한 뷰 모델 전달

현재 사용자에 대한 사용 권한을 설정할 수있는보기를 구현하려고합니다. 각 PermissionTree-Object가 하위 권한을 참조하는 경우 데이터 구조로

은 내가 (권한이 계층 적으로 내 응용 프로그램으로 구성되어 있습니다) 재귀 클래스에 따라 사용

을 :

여기
public class PermissionTree 
{ 
     public Permission Node; //the permission object contains a field of type SqlHierarchyId if that is relevant 
     public bool HasPermission; 
     public IList<PermissionTree> Children; 
    //i cut out the constructors to keep it short ... 
} 

컨트롤러가 같은 모습입니다

@model PermissionTree 
//.... 
@using (Html.BeginForm("Permissions", "Permission", null, FormMethod.Post, new { @class = "stdform stdform2" })) 
{  
<input name="save" title="save2" class="k-button" type="submit" /> 

<div class="treeview"> 
//i am using the telerik kendoUI treeview 
    @(Html.Kendo().TreeView() 
      .Name("Permissions") 
      .Animation(true) 
      .ExpandAll(true) 
      .Checkboxes(checkboxes => checkboxes 
       .CheckChildren(true) 
      ) 
      .BindTo(Model, mapping => mapping 
       .For<PermissionTree>(binding => binding 
       .Children(c => c.Children) 
       .ItemDataBound((item, c) => { 
        item.Text = c.Node.PermissionName; 
        item.Checked = c.HasPermission; 
       }) 

       ) 
      ) 
    ) 
:이 같은 강력한 형식의 뷰를 사용하여 오전에
//this is called to open the view 
public ActionResult Permissions() 
    { 
     //pass the root element which contains all permission elements as children (recursion) 
     PermissionTree permissionTree = PopulateTree();//the fully populated permission-tree 
     return View(permissionTree); 
    } 

//this is called when i submit the form 
    [HttpPost] 
    public ActionResult Permissions(PermissionTree model) 
    { 
     SetPermissions(model); 
     ViewData["PermissionsSaved"] = true; 

     return View(model);//return RedirectToAction("Index"); 
    } 

ok, 버튼을 클릭하면 [HttpPost]으로 장식 된 컨트롤러 동작으로 내 viewmodel을 보내고 싶습니다. 하지만 응용 프로그램을 디버깅 할 때받은 모델에 실제로 내 데이터가 포함되어 있지 않습니다 (null이 아님). 누구나 내 목표를 달성하고 전체 viewmodel을 얻을 수있는 방법을 알고 있습니까?

안부, r3try이

+0

보기에 입력 필드가 있습니까? – ken2k

+0

아니요, 나는 체크 박스가있는 treeview 만 사용합니다. – r3try

+0

모델 바인딩에서 어떤 일이 일어나는지보십시오. http : // stackoverflow.co.kr/questions/4651085/best-practices-for-debugging-asp-net-mvc-binding – ngm

답변

2

내가 여기에 JSON 게시물을 사용하는 것이 더 좋다고 생각한다, 그것은 자바 스크립트 측면에서 개체를 준비하기 쉽습니다.

HTML의 모양이나 요소의 이름을 잘 모르겠다. javascript/Jquery를 사용하여 PermissionTree 클래스 에서처럼 비슷한 이름과 더 얇은 계층/dataTypes를 가진 클라이언트 측 json 객체를 쉽게 만들 수 있습니다. 그리고 JSON

var PermissionTree={Node:{},HasPermission:false,Children:{}} 
$.ajax({ data:PermissionTree 
          type: "POST", 
          url: 'YourController/Permissions', 
          contentType: "application/json; charset=utf-8", 
          dataType: "json", 
          success: function (result) { 
       } 
); 

중요한 것은 트리보기 throuth가는 더 나은 방법을 찾아 자바 스크립트 객체를 구축 할 필요가 그대로 게시하는 아약스 게시물을 사용합니다.

+0

나는 이것을 완전히 이해하지 못한다고 생각합니다 ... 제출 버튼을 클릭하면 자바 스크립트를 사용하여 직렬화 된 객체를 수동으로 생성하고 아약스를 사용하여 컨트롤러에 데이터를 게시해야합니다. 난 정말 MVC에 강하게 입력 된보기가 왜 컨트롤러에 다시 그 viewmodel을 통과하지 못할 이해하지 않는다. 그 모델을 수정하기위한 관점이 아닌가? .. \ * 한숨 \ * 좌절 - 답장을 보내 주셔서 감사합니다! ;) – r3try

+1

문제는 수집 한 모델 모음에 있습니다. 강하게 유형보기를 게시하고 모델을 채우려면보기에 사용 된 적절한 이름 지정 규칙이 필요합니다. HTML에서 당신의 입력은'Children [0] .Chilren [1] .Permission'과 같은 이름을 예로해야합니다. –

+0

JSON 개체를 채우고 Ajax를 사용하여 전달하는 것이 가장 좋은 방법입니다. –

0

난 그게 내가 약간 다른 접근 방식려고 출근하지 못할 같이 노드 추가에 대한

예 : 를 - 버튼을 누릅니다 추가 -> 아약스 호출을 실행 -> 자 NHibernate에 노드를 추가 ->를 호출 새로운 데이터로 다시보기 (신규 노드 포함) AJAX 요청에 의해 호출

컨트롤러 액션 :

[Authorize] 
    [HttpPost] 
    public ActionResult AddPermission(string parentPermissionName, string permissionName) 
    { 
     var pd = ServiceContext.PermissionService.permissionDao; 
     Permission parentPermission = pd.GetPermissionByName(parentPermissionName); 
     if (parentPermission == null) { 
      parentPermission = pd.GetRoot(); 
     } 

     if (parentPermission != null && !string.IsNullOrEmpty(permissionName) && !pd.PermissionExists(permissionName))//only add with a name 
     { 
      pd.AddPermission(parentPermission, permissionName); 
     } 
     //refresh data 
     PermissionTree permissionTree = LoadTreeSQLHierarchy(null, false);//start at root 
     return View("Permissions", permissionTree); 
    } 

Ajax 요청 :

function addNode() { 
    //... get the data here 
    var addData = { parentPermissionName: selectedNodeName, permissionName: newNodeName }; 

    $.ajax(
     { 
      data: addData, 
      type: "POST", 
      url: '@Url.Action("AddPermission", "Permission")', 
      dataType: "json", 
      success: function (result) { 
       //$('.centercontent').html(response);//load to main div (?) 
       return false; 
      }, 
      error: function (xhr, ajaxOptions, thrownError) { 
       alert(xhr.status + ":" + thrownError); 
       return false; 
      } 
     } 
    ); 
    return false; 
} 

하지만 내가 이것을 실행하면 json.parse가 잘못된 문자를 치는 오류가 발생합니다.이 오류는 아약스의 오류 함수에서 경고가 발생합니다. 그 메시지로 판단하면 문제는 내가 HTML을 반환하지만 아약스 호출은 json을 기대한다고 말합니다 ... 하지만 새로운 데이터로 내보기를 다시로드하는 올바른 방법은 무엇입니까? 어떻게 든 아약스 호출에 전혀 돌아 가지 않고 호출 된 컨트롤러 메소드 만 실행하도록 할 수 있습니까?