programing

JavaScript / jQuery를 사용하여 ASP.NET MVC의 다른 페이지로 리디렉션

nasanasas 2020. 11. 3. 08:06
반응형

JavaScript / jQuery를 사용하여 ASP.NET MVC의 다른 페이지로 리디렉션


JavaScript / jQuery / Ajax를 사용하여 ASP.NET MVC 3.0의 한 페이지에서 다른 페이지로 리디렉션하고 싶습니다. 버튼 클릭 이벤트에서 아래와 같은 JavaScript 코드를 작성했습니다.

function foo(id)
{
    $.post('/Branch/Details/' + id);
}

내 컨트롤러 코드는 다음과 같습니다.

public ViewResult Details(Guid id)
{
     Branch branch = db.Branches.Single(b => b.Id == id);
     return View(branch);
}

버튼을 클릭하면 BranchController 내부에서 Details 액션을 호출하지만 Details 뷰로 돌아 가지 않습니다.

오류나 예외가 발생하지 않았습니다. Firebug 에서 상태 200 OK를 표시합니다 . 내 코드에서 무엇이 잘못되었으며 세부 정보보기 페이지로 리디렉션하려면 어떻게해야합니까?


$ .post AJAX 호출에서 성공 콜백을 구독하고 있지 않습니다. 요청이 실행되었지만 결과로 아무것도하지 않음을 의미합니다. 결과로 유용한 작업을 수행하려면 다음을 시도하십시오.

$.post('/Branch/Details/' + id, function(result) {
    // Do something with the result like for example inject it into
    // some placeholder and update the DOM.
    // This obviously assumes that your controller action returns
    // a partial view otherwise you will break your markup
});

반면에 리디렉션하려면 AJAX가 절대 필요하지 않습니다. AJAX는 동일한 페이지에 머무르고 일부만 업데이트하려는 경우에만 사용합니다.

따라서 브라우저 만 리디렉션하려는 경우 :

function foo(id) {
    window.location.href = '/Branch/Details/' + id;
}

참고로 이렇게 URL을 하드 코딩해서는 안됩니다. ASP.NET MVC 응용 프로그램에서 URL을 처리 할 때는 항상 URL 도우미를 사용해야합니다. 그래서:

function foo(id) {
    var url = '@Url.Action("Details", "Branch", new { id = "__id__" })';
    window.location.href = url.replace('__id__', id);
}

뷰에서 숨겨진 변수를 사용한 다음 해당 변수를 사용하여 JavaScript 코드에서 게시하면됩니다.

보기에 내 코드가 있습니다.

@Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));

이제 JavaScript 파일에서 다음과 같이 사용할 수 있습니다.

 var url = $("#RedirectTo").val();
 location.href = url;

그것은 나에게 매력처럼 작용했다. 나는 그것이 당신에게도 도움이되기를 바랍니다.


당신이 사용할 수있는:

window.location.href = '/Branch/Details/' + id;

그러나 Ajax 코드는 성공 또는 오류 기능 없이는 불완전합니다.


// in the HTML code I used some razor
@Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));

// now down in the script I do this
<script type="text/javascript">

var url = $("#RedirectTo").val();

$(document).ready(function () {
    $.ajax({
        dataType: 'json',
        type: 'POST',
        url: '/Controller/Action',
        success: function (result) {
            if (result.UserFriendlyErrMsg === 'Some Message') {
                // display a prompt
                alert("Message: " + result.UserFriendlyErrMsg);
                // redirect us to the new page
                location.href = url;
            }
            $('#friendlyMsg').html(result.UserFriendlyErrMsg);
        }
    });
</script>

<script type="text/javascript">
    function lnkLogout_Confirm()
    {
        var bResponse = confirm('Are you sure you want to exit?');

        if (bResponse === true) {
            ////console.log("lnkLogout_Confirm clciked.");
            var url = '@Url.Action("Login", "Login")';
            window.location.href = url;
        }
        return bResponse;
    }

</script>

아래 코드를 확인하면 도움이 될 것입니다.

<script type="text/javascript">
  window.opener.location.href = '@Url.Action("Action", "EventstController")', window.close();
</script>

참고URL : https://stackoverflow.com/questions/8148632/redirecting-to-another-page-in-asp-net-mvc-using-javascript-jquery

반응형