2013-08-07 1 views
2

MVC4 앱에서 jQuery 파일 업로드 플러그인 (https://github.com/blueimp/jQuery-File-Upload)을 사용하고 있습니다.부분 뷰로드시 jQuery 이벤트가 연결되지 않음

파일 업로드 기능 (업로드 된 파일 및 업로드 된 파일)은 부분보기에 포함되어 있습니다.

그래서 파일 업로드 부분보기가 포함 된 여러 가지보기가 있습니다. 파일이 업로드되면 첨부 컨트롤러의 저장 작업이 시작됩니다. 이것은 파일의 저장을 처리 한 다음 사이트의이 특정 영역에 대한 파일의 업데이트 된 목록을 검색합니다. 뷰는 fileupload jQuery로 리턴 된 다음 Html을 부모 페이지의 div에 삽입합니다 (#_attachments).

이 모든 것이 올바르게 렌더링됩니다. 내가 가지고있는 문제는 파일 업로드가 수행되고 부분 뷰가 jQuery를 통해 다시로드 된 후에 파일 업로드가 더 이상 작동하지 않는다는 것입니다.

이벤트가 더 이상 #fileUpload 컨트롤에 연결되지 않은 것 같습니다. 나는 'on'메쏘드를 사용해 보았지만 이것 역시 효과가없는 것 같습니다.

부분보기 스크립트

$(function() { 
     $('#fileUpload').fileupload({ 
      url: "/Attachment/Save", 
      done: function (e, data) { 
       // "data.result" will contain the response data 
       $("#fileUploadProgress").hide(); 
       $("#_attachments").html(data.result); 
      }, 
      progressall: function (e, data) { 
       var progress = parseInt(data.loaded/data.total * 100, 10); 
       $("#fileUploadProgress").show(); 
       $("#fileUploadProgress .bar").css("width", progress + "%"); 
      } 
     }); 
    }); 

컨트롤러/액션

[HttpPost] 
     public ActionResult Save() 
     { 

      // Get a reference to the file that our jQuery sent. Even with multiple files, they will all be their own request and be the 0 index 
      HttpPostedFileBase file = HttpContext.Request.Files[0]; 

      int ncpId = Convert.ToInt32(Request.Form["ncpId"]); 
      int stage = Convert.ToInt32(Request.Form["stage"]); 

      ncpRepository.SaveAttachmentToDb(file, CurrentUser.UserId, ncpId, stage); 

      //return the partial view to refresh the list of files 
      var attachments = ncpRepository.GetAttachmentsForRecord(ncpId); 
      var attachmentsViewModel = AutoMapper.Mapper.Map<IQueryable<Attachment>, List<AttachmentViewModel>>(attachments); 

      ViewData["Stage"] = stage; 

      return PartialView("_StageAttachments", attachmentsViewModel); 
     } 
+0

부분적으로로드 될 때마다 부분 스크립트를 실행하고 있습니까? 여기에 "on"바인더가 필요하지 않을 때마다 매번 fileupload 플러그인을 초기화해야한다고 생각합니다. – Moeri

답변

1

이 때문에 더 이상 #fileUpload 제어에 부착되는 이벤트가 될 수 있다는 것을 나타납니다 .

네, 그 모양입니다. 이제 코드에 몇 가지 문제가 있습니다. 첫 번째 문제는이 자바 스크립트 코드가 부분 뷰 안에 있음을 언급했다는 것입니다. 그러나 부분 뷰에는 스크립트가 포함되어서는 안됩니다. Javascript는 별도의 파일에 속합니다. 또한 id 셀렉터 인 $('#fileUpload') 셀렉터를 사용한 것 같습니다. 그럼 당신은 그 부분적인 견해를 많이 가지고 있다고하셨습니다. 따라서 전체 HTML 내에서 지정된 ID를 가진 요소를 하나만 가질 수 있기 때문에 잠재적으로 DOM이 손상되었을 수 있습니다.

그럼 (한 번 기본보기에서 참조) 별도의 파일로이 스크립트를 이동하여이 문제를 해결 시작하자되는 DOM의 새로운 요소로 파일 업로드 컨트롤 다시 연결합니다 :이에서

var attachFileUploads = function() { 
    $('.fileUpload').fileupload({ 
     url: "/Attachment/Save", // TODO: Never hardcode an url like that, read it from an HTML 5 data-* attribute on the corresponding file input such as data-url="@Url.Action("Save", "Attachment")" 
     done: function (e, data) { 
      $("#fileUploadProgress").hide(); 
      $("#_attachments").html(data.result); 
      attachFileUploads(); // <!-- reattach the fileupload plugin 
     }, 
     progressall: function (e, data) { 
      var progress = parseInt(data.loaded/data.total * 100, 10); 
      $("#fileUploadProgress").show(); 
      $("#fileUploadProgress .bar").css("width", progress + "%"); 
     } 
    }); 
}; 

$(attachFileUploads); 

을 예 저는 두 개 이상의 파일 입력을 가질 수 있다고 가정하는 클래스 선택기 $('.fileUpload')을 사용했습니다. 이 클래스를 할당했고 앞에서 언급했듯이 고유해야하는 id을 제거했는지 확인하십시오.

+0

감사합니다. 파일 업로드 컨트롤은 부분 뷰에만 있으므로 페이지 당 한 번만 선언되므로이 인스턴스에서는 id를 사용하는 것이 좋습니다. 접근 방식을 반영하도록 코드를 업데이트하고 어떻게 진행되는지 살펴 보겠습니다. – sparkymark75

+0

훌륭하고 훌륭한 작품입니다. 하드 코딩 된 URL을 제거하고 data-url 값으로 대체했습니다. – sparkymark75