ASP.NET MVC에서 jQuery를 사용하여 부분 뷰 렌더링 jquery를 사용하여 부분보기를 어떻게

jquery를 사용하여 부분보기를 어떻게 렌더링합니까?

부분 뷰를 다음과 같이 렌더링 할 수 있습니다.

<% Html.RenderPartial("UserDetails"); %>

jquery를 사용하여 어떻게 똑같이 할 수 있습니까?



답변

jQuery 만 사용하여 부분보기를 렌더링 할 수 없습니다. 그러나 부분 뷰를 렌더링하고 jQuery / AJAX를 사용하여 페이지에 추가하는 메소드 (액션)를 호출 할 수 있습니다. 아래에는 버튼의 데이터 속성에서 작업에 대한 URL을로드하고 부분보기에 포함 된 DIV를 업데이트 된 내용으로 바꾸는 GET 요청을 발생시키는 버튼 클릭 핸들러가 있습니다.

$('.js-reload-details').on('click', function(evt) {
    evt.preventDefault();
    evt.stopPropagation();

    var $detailDiv = $('#detailsDiv'),
        url = $(this).data('url');

    $.get(url, function(data) {
        $detailDiv.replaceWith(data);
    });
});

여기서 사용자 컨트롤러에는 다음과 같은 작업을 수행하는 details라는 작업이 있습니다.

public ActionResult Details( int id )
{
    var model = ...get user from db using id...

    return PartialView( "UserDetails", model );
}

이것은 부분보기가 ID가있는 컨테이너라고 가정 detailsDiv하여 전체 결과를 호출 결과의 내용으로 바꿉니다.

부모보기 버튼

 <button data-url='@Url.Action("details","user", new { id = Model.ID } )'
         class="js-reload-details">Reload</button>

User제어기 이름이며의 details조치 이름입니다 @Url.Action(). UserDetails 부분보기

<div id="detailsDiv">
    <!-- ...content... -->
</div>


답변

나는 이것을하기 위해 ajax load를 사용했다.

$('#user_content').load('@Url.Action("UserDetails","User")');


답변

@ tvanfosson은 그의 대답으로 흔들립니다.

그러나 js 내에서 개선하고 작은 컨트롤러 검사를 제안합니다.

@Url헬퍼를 사용 하여 액션을 호출하면 형식화 된 html을 받게됩니다. .html실제 요소 ( .replaceWith)가 아닌 컨텐츠 ( ) 를 업데이트하는 것이 좋습니다 .

에 대한 추가 정보 : jQuery의 replaceWith ()와 html ()의 차이점은 무엇입니까?

$.get( '@Url.Action("details","user", new { id = Model.ID } )', function(data) {
    $('#detailsDiv').html(data);
}); 

이것은 내용이 여러 번 변경 될 수있는 트리에서 특히 유용합니다.

컨트롤러에서 요청자에 따라 조치를 재사용 할 수 있습니다.

public ActionResult Details( int id )
{
    var model = GetFooModel();
    if (Request.IsAjaxRequest())
    {
        return PartialView( "UserDetails", model );
    }
    return View(model);
}


답변

시도 할 수있는 또 다른 것은 (tvanfosson의 답변을 기반으로) 다음과 같습니다.

<div class="renderaction fade-in"
    data-actionurl="@Url.Action("details","user", new { id = Model.ID } )"></div>

그런 다음 페이지의 스크립트 섹션에서

<script type="text/javascript">
    $(function () {
        $(".renderaction").each(function (i, n) {
            var $n = $(n),
                url = $n.attr('data-actionurl'),
                $this = $(this);

            $.get(url, function (data) {
                $this.html(data);
            });
        });
    });

</script>

이것은 ajax를 사용하여 @ Html.RenderAction을 렌더링합니다.

그리고 모든 fany sjmansy를 만들기 위해이 CSS를 사용하여 페이드 인 효과를 추가 할 수 있습니다.

/* make keyframes that tell the start state and the end state of our object */
@-webkit-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@-moz-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }

.fade-in {
    opacity: 0; /* make things invisible upon start */
    -webkit-animation: fadeIn ease-in 1; /* call our keyframe named fadeIn, use animattion ease-in and repeat it only 1 time */
    -moz-animation: fadeIn ease-in 1;
    -o-animation: fadeIn ease-in 1;
    animation: fadeIn ease-in 1;
    -webkit-animation-fill-mode: forwards; /* this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)*/
    -o-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    -webkit-animation-duration: 1s;
    -moz-animation-duration: 1s;
    -o-animation-duration: 1s;
    animation-duration: 1s;
}

내가 사랑하는 사람 mvc 🙂


답변

컨트롤러에서 “UserDetails”부분보기 또는 컨트롤의 렌더링 결과를 반환하는 액션을 만들어야합니다. 그런 다음 jQuery에서 Http Get 또는 Post를 사용하여 Action을 호출하여 렌더링 된 HTML을 표시하십시오.


답변

동일한 결과를 얻기 위해 표준 Ajax 호출 사용

        $.ajax({
            url: '@Url.Action("_SearchStudents")?NationalId=' + $('#NationalId').val(),
            type: 'GET',
            error: function (xhr) {
                alert('Error: ' + xhr.statusText);

            },
            success: function (result) {

                $('#divSearchResult').html(result);
            }
        });




public ActionResult _SearchStudents(string NationalId)
        {

           //.......

            return PartialView("_SearchStudents", model);
        }


답변

나는 이렇게했다.

$(document).ready(function(){
    $("#yourid").click(function(){
        $(this).load('@Url.Action("Details")');
    });
});

세부 사항 방법 :

public IActionResult Details()
        {

            return PartialView("Your Partial View");
        }