首页 > 解决方案 > send ajax post request from partial view in asp.net core razor pages

问题描述

I am trying to send POST Ajax from partial view. this is my partial view:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="../css/simple-sidebar.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="~/css/simple-sidebar.css">

<div id="sidebar">
    <div class="toggle-btn" onclick="toggleSidebar()">
        <span></span>
        <span></span>
        <span></span>
    </div>
    <div id="links">
        <a href="" onclick='MainTabs()' id="tab1">tab1</a>

    </div>
</div>

<script type="text/javascript">

    function MainTabs() {
        console.log('first');

        $(document).ready(function () {
            $.ajax({
                url: "/Main/getddl",
            type: "POST",
            dataType: "json",
                success: function (response) {
                    console.log(Session["switch"]);
                console.log('ok');
            },
            failure: function (response) {
                console.log('error');
            }
            });
        });
    }
</script>

This is parent .cs code:

public class MainModel : PageModel {

    public void getddl()
    {
        HttpContext.Session.SetString("ddl", "ddl");
    }

}

I have 'first' printed in console, but then immediately have an error also error doesn't remain and disappears in a sec.

POST https://localhost:33444/getddl 404

标签: jqueryajaxasp.net-corepartial-viewsrazor-pages

解决方案


我发现问题导致了这种行为。我有侧边栏,并且有一种方法可以激活它:

function toggleSidebar() {
        document.getElementById("sidebar").classList.toggle('active');
    }

由于这个侧边栏是活动类,它对主页一无所知。单击其中一个项目后,我尝试删除活动类,但尚未成功。

$(document).ready(function () {

        $('#MainTabs').click(function () {
            //e.preventDefault();
            //$('.sidebar a').removeClass('active');
            //$(this).addClass('active');
            var id = $(this).attr("id");
            $('#' + id).siblings().find(".active").removeClass("active");
            $('#' + id).addClass("active");
            localStorage.setItem("selectedolditem", id);
            var fullName = $('#texboxFullName').val();
            alert(id);
            $.ajax({
                type: 'GET',
                data: { fullName: fullName },
                url: '@Url.Page("Main", "Demo2")',
                success: function (result) {
                    $('#result2').html(result);
                }
            })
        });
    });

有什么帮助吗?


推荐阅读