'Render partial view on button click in asp.net core

Based on which button is clicked i want to render a partial View inside a div element. If button1 is clicked then Partial View1 is rendered and if button2 is clicked then Partial View2 is rendered. How can i do it.

Main View:enter code here

<button id="button1">One</button>
<button id="button2">Two</button>

<div id="search">
//Render Partial view here based on which button is clicked.
</div>

Partial View1:

<p>In Partial View1</p>

Partial View2:

<p>In Partial View2</p>

   

After i click the blue button, i want partial page to be rendered in Div area below the blue button. But its rendering above the button in grey area which is my common layout area.

Before click enter image description here

After enter image description here


I tried this code but the problem is that partial view is loading but not within the div element.

        <input id="btnSearch" type="button" class="btn btn-primary" value="Search" />
        
        <div id="students">
           
        </div>

<script>
    $('#btnSearch').on('click',
        function (e) {
            $.ajax({
                url: '/Home/About',
                    type: 'POST',
                    cache: false,
                    async: true,
                dataType: "html"
                

                })
                .done(function(result) {
                    $('#students').html(result);
                }).fail(function(xhr) {
                    console.log('error : ' + xhr.status + ' - ' + xhr.statusText + ' - ' + xhr.responseText);
                });

        });

</script>


Solution 1:[1]

I think the code you posted should work, but you need to query the right endpoint of your home controller. Given your minimal modified code (see the ajax url):

        <input id="btnSearch" type="button" class="btn btn-primary" value="Search" />

        <div id="students">

        </div>

<script>
    $('#btnSearch').on('click',
        function (e) {
            $.ajax({
                url: '/Home/View2',
                    type: 'POST',
                    cache: false,
                    async: true,
                dataType: "html"


                })
                .done(function(result) {
                    $('#students').html(result);
                }).fail(function(xhr) {
                    console.log('error : ' + xhr.status + ' - ' + xhr.statusText + ' - ' + xhr.responseText);
                });

        });

</script>

And your HomeController.cs should have such a second method:

public IActionResult View2(){
  return PartialView();
}

Edit I guess these pages could help you to get a rough idea of controllers and the handling:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1