Development Tip

Bootstrap 모달 창을 PartialView로 사용

yourdevel 2020. 11. 23. 20:16
반응형

Bootstrap 모달 창을 PartialView로 사용


내가 사용하는보고 있었다 트위터 부트 스트랩 모달 창을 부분보기로. 그러나 나는 그것이 이러한 방식으로 사용되도록 설계되었다고 생각하지 않습니다. 상당히 정적 인 방식으로 사용되도록 의도 된 것 같습니다. 그럼에도 불구하고 부분보기로 사용할 수 있으면 멋지다고 생각합니다.

예를 들어 게임 목록이 있다고 가정 해 보겠습니다. 주어진 게임에 대한 링크를 클릭하면 서버에 데이터를 요청한 다음 현재 페이지 "위에있는"모달 창에 해당 게임에 대한 정보를 표시하고 싶습니다.

나는 약간의 연구를했고 비슷하지만 완전히 같지는 않은 이 게시물발견 했습니다 .

성공 또는 실패로 이것을 시도한 사람이 있습니까? 누구든지 jsFiddle에 뭔가를 가지고 있거나 그들이 공유 할 소스가 있습니까?

당신의 도움을 주셔서 감사합니다.


예, 우리는 이것을했습니다.

Index.cshtml에는 다음과 같은 내용이 있습니다 ..

<div id='gameModal' class='modal hide fade in' data-url='@Url.Action("GetGameListing")'>
   <div id='gameContainer'>
   </div>
</div>

<button id='showGame'>Show Game Listing</button>

그런 다음 동일한 페이지 (인라인 또는 별도의 파일)에 대한 JS에서 다음과 같은 내용을 갖게됩니다.

$(document).ready(function() {
   $('#showGame').click(function() {
        var url = $('#gameModal').data('url');

        $.get(url, function(data) {
            $('#gameContainer').html(data);

            $('#gameModal').modal('show');
        });
   });
});

다음과 같은 컨트롤러의 메소드로 ..

[HttpGet]
public ActionResult GetGameListing()
{
   var model = // do whatever you need to get your model
   return PartialView(model);
}

물론 Views 폴더 안에 GetGameListing.cshtml이라는 뷰가 필요합니다 ..


mustache.js 및 템플릿 으로이 작업을 수행합니다 (자바 스크립트 템플릿 라이브러리를 사용할 수 있음).

내 생각에는 다음과 같은 것이 있습니다.

<script type="text/x-mustache-template" id="modalTemplate">
    <%Html.RenderPartial("Modal");%>
</script>

... 내 템플릿을 다음과 같은 부분보기로 유지할 수 있습니다 Modal.ascx.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    <div>
        <div class="modal-header">
            <a class="close" data-dismiss="modal">&times;</a>
            <h3>{{Name}}</h3>
        </div>
        <div class="modal-body">
            <table class="table table-striped table-condensed">
                <tbody>
                    <tr><td>ID</td><td>{{Id}}</td></tr>
                    <tr><td>Name</td><td>{{Name}}</td></tr>
                </tbody>
            </table>
        </div>
        <div class="modal-footer">
            <a class="btn" data-dismiss="modal">Close</a>
        </div>
    </div>

내보기에서 각 모달에 대한 자리 표시자를 만듭니다.

<%foreach (var item in Model) {%>
    <div data-id="<%=Html.Encode(item.Id)%>"
         id="modelModal<%=Html.Encode(item.Id)%>" 
         class="modal hide fade">
    </div>
<%}%>

... jQuery를 사용하여 ajax 호출을 수행합니다.

<script type="text/javascript">
    var modalTemplate = $("#modalTemplate").html()
    $(".modal[data-id]").each(function() {
        var $this = $(this)
        var id = $this.attr("data-id")
        $this.on("show", function() {
            if ($this.html()) return
            $.ajax({
                type: "POST",
                url: "<%=Url.Action("SomeAction")%>",
                data: { id: id },
                success: function(data) {
                    $this.append(Mustache.to_html(modalTemplate, data))
                }
            })
        })
    })
</script>

그런 다음 어딘가에 트리거가 필요합니다.

<%foreach (var item in Model) {%>
    <a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>">
        <%=Html.Encode(item.DutModel.Name)%>
    </a>
<%}%>

나는 내가 여기 에서 찾은 하나의 좋은 예를 사용하여 이것을 달성 했다 . 이 예제에서 사용 된 jquery 대화 상자를 Twitter Bootstrap Modal 창으로 대체했습니다.


완전하고 명확한 예제 프로젝트 http://www.codeproject.com/Articles/786085/ASP-NET-MVC-List-Editor-with-Bootstrap-Modals 부트 스트랩을 사용하여 엔티티 작업 모달 생성, 편집 및 삭제를 표시하고 코드도 포함합니다. 해당 엔터티 작업에서 반환 된 결과 처리 (c #, JSON, javascript)


나는 이것을하기 위해 AJAX를 사용한다. 일반적인 트위터 모달 템플릿 html로 부분을 가지고 있습니다.

<div class="container">
  <!-- Modal -->
  <div class="modal fade" id="LocationNumberModal" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">
            &times;
          </button>
          <h4 class="modal-title">
            Serial Numbers
          </h4>
        </div>
        <div class="modal-body">
          <span id="test"></span>
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">
            Close
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

Then you have your controller method, I use JSON and have a custom class that rendors the view to a string. I do this so I can perform multiple ajax updates on the screen with one ajax call. Reference here: Example but you can use an PartialViewResult/ActionResult on return if you are just doing the one call. I will show it using JSON..

And the JSON Method in Controller:

public JsonResult LocationNumberModal(string partNumber = "")
{
  //Business Layer/DAL to get information
  return Json(new {
      LocationModal = ViewUtility.RenderRazorViewToString(this.ControllerContext, "LocationNumberModal.cshtml", new SomeModelObject())
    },
    JsonRequestBehavior.AllowGet
  );
}

And then, in the view using your modal: You can package the AJAX in your partial and call @{Html.RenderPartial... Or you can have a placeholder with a div:

<div id="LocationNumberModalContainer"></div>

then your ajax:

function LocationNumberModal() {
  var partNumber = "1234";

  var src = '@Url.Action("LocationNumberModal", "Home", new { area = "Part" })'
    + '?partNumber='' + partNumber; 

  $.ajax({
    type: "GET",
    url: src,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
      $("#LocationNumberModalContainer").html(data.LocationModal);
      $('#LocationNumberModal').modal('show');
    }
  });
};

Then the button to your modal:

<button type="button" id="GetLocBtn" class="btn btn-default" onclick="LocationNumberModal()">Get</button>

Put the modal and javascript into the partial view. Then call the partial view in your page. This will handle form submission too.

Partial View

<div id="confirmDialog" class="modal fade" data-backdrop="false">
 <div class="modal-dialog" data-backdrop="false">
    <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title">Missing Service Order</h4>
        </div>
        <div class="modal-body">
            <p>You have not entered a Service Order. Do you want to continue?</p>
        </div>
        <div class="modal-footer">
            <input id="btnSubmit" type="submit" class="btn btn-primary" 
              value="Submit" href="javascript:" 
               onClick="document.getElementById('Coordinate').submit()" />
            <button type="button" class="btn btn-default" data- 
                                               dismiss="modal">Cancel</button>
        </div>
    </div>
  </div>
</div>

Javascript

  <script type="text/javascript" language="javascript">
$(document).ready(function () {
    $("#Coordinate").on('submit',
        function (e) {
            if ($("#ServiceOrder").val() == '') {
                e.preventDefault();
                $('#confirmDialog').modal('show');
               }
            });
    });
</script>

Then just call your partial inside the form of your page.

Create.cshtml

 @using (Html.BeginForm("Edit","Home",FormMethod.Post, new {id ="Coordinate"}))
 {
     //Form Code

     @Html.Partial("ConfirmDialog") 
 }

참고URL : https://stackoverflow.com/questions/11231862/using-bootstrap-modal-window-as-partialview

반응형