2014-06-13 1 views
0

IEnumerable에서 파생 된 사용자 지정 개체가 있습니다. 이 콜렉션은 다른 오브젝트의 콜렉션을 포함하는 오브젝트를 포함하기 때문에 꽤 복잡합니다. 간단히 말해, 다중 차원 배열입니다.JQuery를 사용하여 컨트롤러에서보기로 사용자 지정 컬렉션 개체 전달

서버 호출로 항목이 채워지는 드롭 다운 목록이 있으며 특정 항목을 선택하면 서버가 해당 항목의 관련 컬렉션 개체를 가져 오기 위해 서버를 호출합니다.

이 코드를 상속했으며 처음에는 첫 번째 드롭 다운을 선택하면 두 번째 드롭 다운이 활성화되고 사용자가 단일 항목을 선택합니다. 두 번째 드롭 다운은 컬렉션의 항목으로 채워집니다 (컬렉션 자체는 항목의 이름과 ID 번호를 가져 오기 위해 파싱됩니다).

이제 두 번째 드롭 다운 대신 실제로 컬렉션을 뷰로 되돌리고 내 뷰 루프를 반복하여 컬렉션의 내용과 모든 좋은 내용을 표시하려고합니다.

내 질문은 내 컨트롤러에서 내보기로이 컬렉션 개체를 전송할 수 있습니다.

다음은 컨트롤러의 드롭 다운 값을 기반으로 컬렉션을 잡는 코드입니다.

public ActionResult GetWorkbooks(string term, int projectId = -1) 
    { 
     if (this.SelectedProject != projectId) 
     { 
      try 
      { 
       WorkBookDataManager dataManager = new WorkBookDataManager(); 
       this.WorkbookColl = dataManager.GetWorkBooksById(null, projectId, null); 
       this.SelectedProject = projectId; 
      } 
      catch (Exception exc) 
      { 
       log.Error("Could not load projects", exc); 
      } 
     } 

     return this.View("_Workbook", this.WorkbookColl); 
    } 

이 코드는 모델로 컬렉션 부분 뷰를 반환합니다. 그러나 드롭 다운 값을 선택하면 기존 JQuery 코드와 함께 어떻게 사용할 수 있습니까? 여기

코드 드롭 다운입니다 :

// Populate the first drop down 
var loadProjects = function (request, response) { 
    $.ajax({ 
     url: $("#projects").attr("data-vs-autocomplete"), 
     dataType: "json", 
     type: "POST", 
     data: { term: request.term } 
    }) 
    .always(function (data, status) { getResponse(response, data, status); }); 
}; 

// If the first drop down has an item selected enable the second drop down 
var projectSelected = function (event, ui) { 
    var projectId = $("#projects").data(VS_AUTOCOMPLETE_VALUE); 

    var enable = projectId ? false : true; 
    /*$("#workbooks").prop('disabled', enable); 

    $("#workbooks").val(""); 
    $("#workbooks").data(VS_AUTOCOMPLETE_VALUE, ""); 
    $("#workbooks").data(VS_AUTOCOMPLETE_TEXT, "");*/ 
    $("#workbook").html("<p>No workbook selected</p>"); 
}; 

// Function to get the second drop down items 
// This is the function I think needs to be modified to accept the collection object from the server 
var loadWorkbooks = function (request, response) { 
    $.ajax({ 
     url: $("#workbooks").attr("data-vs-autocomplete"), 
     dataType: "json", 
     type: "POST", 
     data: 
      { 
       term: request.term, 
       projectId: $("#projects").data(VS_AUTOCOMPLETE_VALUE) 
      } 
    }) 
     .always(function (data, status) { getResponse(response, data, status); }); 
}; 

// Second drop down -> This needs to be removed 
var workbookSelected = function (event, ui) { 
    $("#workbooks").blur(); // this prevents the workbook dropdown from focusing. 
    LoadWorkbook(); 
}; 


// These functions populated the drop downs with items 
Autocomplete($("#projects"), 
    { autoFocus: true, 
     minLength: 0, 
     source: loadProjects, 
     select: projectSelected 
    }); 

Autocomplete($("#workbooks"), 
    { autoFocus: true, 
     minLength: 0, 
     source: loadWorkbooks, 
     select: workbookSelected 
    }); 

내가 더 나은이 모든 작업을 수행하는 방법 및 구조 조정 컨트롤러 및/또는 JQuery와있다, 그래서 만약이 간단하게 할, 내가 (모든 귀를입니다 눈).

자세한 정보가 필요한지 또는 명확하지 않은 부분이 있으면 알려주십시오. 감사합니다.

답변

2

"우수 사례"는 단일 책임 원칙, 즉 드롭 다운에 표시해야하는 데이터를 가져 오는 별도의 조치와 ​​부분보기로 렌더링되는 동일한 데이터입니다. 기본적으로 모델을 가져 오는 메소드와 모델을 순차적으로 직렬화하고 JSON 형태로 리턴하는 하나의 조치가 필요합니다. 부분보기가 반환됩니다. 컨트롤러 :

private Workbook GetWorkbooksByProject(int projectId) 
{ 
    WorkBookDataManager dataManager = new WorkBookDataManager(); 
    var workbookColl = dataManager.GetWorkBooksById(null, projectId, null); 
    return workbookColl; 
} 

public JsonResult GetWorkbooks(int projectId) 
{ 
    var model = GetWorkbooksByProject(projectId); 
    return Json(model, JsonRequestBehavior.AllowGet); 
} 

public ActionResult WorkbooksList(string term, int projectId = -1) 
{ 
    if (this.SelectedProject != projectId) 
    { 
     try 
     { 
      this.WorkbookColl = GetWorkbooksByProject(projectId); 
      this.SelectedProject = projectId; 
     } 
     catch (Exception exc) 
     { 
      log.Error("Could not load projects", exc); 
     } 
    } 

    return this.View("_Workbook", this.WorkbookColl); 
} 

클라이언트 측에서 당신은 GetWorkbooks 액션 메소드에 데이터를 게시 할 URL을 변경해야합니다 그리고 당신은 갈 수 있습니다.

이 방법의 장점은 통합 문서 목록을 검색하는 것보다 드롭 다운을 채우는 것이 다른 논리를 실행하지 않으며 클라이언트 측에서는 바인딩 프레임 워크 (예 : KnockoutJS) 또는 일반 자바 스크립트를 사용하여 모델을 렌더링 할 수 있다는 것입니다. html 마크 업은 앞으로 단순 드롭 다운에서보다 복잡한 UI로 변경 될 것입니다.

관련 문제