Adding a partial view with JQuery get() method

When we want to add partial views there are a lot of ways to implement. One easy way is using get method provided by JQuery.

Here is a simple script written in JavaScript to change partial views according to user inputs.

             document.getElementById("GetViewsbyPageId").onchange = function () {
                var pageId = $("#GetViewsbyPageId").val();
                if (pageId != 0) {
                    $("#LoadViewsbyPageId").show();
                  //sending a get request
                    $.get('page'+pageId+".html",function (data) {
                        /* data is the pure html returned from get method, load it to your page */
                        $('#LoadViewsbyPageId').html(data);      

                    });
                } else {
                    $("#LoadViewsbyPageId").hide();

                }
             }        

What happens in the script???

  • Detect change in a select element which has Id "GetViewsbyPageId"
  • If the value of that element is not 0 send a get request to get relevant HTML page
  • Display data returned from get request in a DIV which has ID "LoadViewsbyPageId" 

A Complete example

<html>
    <head>    
        <style>
            #LoadViewsbyPageId{
                display: none;
                border: 1px solid gray;
                margin: 5%;
                padding: 2%;
            }
        </style>
    </head>
    <body>
        <h2>Select Page Demo</h2>
        <label>Page Name</label>
                    <select id="GetViewsbyPageId" >
                        <option value="0" >Select Page</option>
                        <option value="1" >Page 1</option>
                        <option value="2" >Page 2</option>
                        <option value="3" >Page 3</option>
                    </select>
        
        <div id ="LoadViewsbyPageId">
                                     
        </div>         
    
        <script src="jquery-1.11.3.js"></script>
        <script>
              document.getElementById("GetViewsbyPageId").onchange = function () {
                var pageId = $("#GetViewsbyPageId").val();
                if (pageId != 0) {
                    $("#LoadViewsbyPageId").show();
                    $.get('page'+pageId+".html",function (data) {
                        /* data is the pure html returned from get method, load it to your page */
                        $('#LoadViewsbyPageId').html(data);      

                    });
                } else {
                    $("#LoadViewsbyPageId").hide();

                }
             }        
        </script>
    </body>
</html>

You can find this example with other resources resources from here

No comments:

Post a Comment