To Call Controller From Javascript in Ajax

    Normally to call the Controller Function from javascript or jquery to the controller need to use Ajax to render data Like as below :

On Javascript Page Document Load :

$.ajax({
            url: "/GetBloggers",
            type: "GET",
            success: function (data) {                
                var $select = $('#Name');
                $select.html('');                
                $.each(data, function (index, value) {
                    // append an <option> for each item in returned list.                
                    $select.append('<option id="' + value.BloggerID+ '">' + value.Name+ '</option>');
                });
            },
            error: function (error) {
                alert(JSON.stringify(error));
            }
        })

 function OnChangeName(s) {
        var id = s[s.selectedIndex].id;
        var name = s[s.selectedIndex].value;
        document.getElementById("ID").value = id;
        document.getElementById("name").value = name;
        //alert("The Id of " + name + " is " + id);
    }



On View Page :
 <select id="Name" onchange="OnChangeName(this)"></select>
 <input type="text" id="ID" />
    <input type="text" id="name" />




On Controller :

public List<Bloggers> GetBloggers()
         {
             List<Bloggers> lstBloggers = new List<Bloggers>()
             {
                 new Bloggers { BloggerID = "1", Name= "Jesse Liberty ", Technology = "XAML"},
                 new Bloggers { BloggerID = "2" , Name = "Michael Crump" , Technology = "XAML"},
                 new Bloggers { BloggerID = "3" , Name = "Chris Eargel" , Technology = "C Sharp"},
                 new Bloggers { BloggerID = "4" , Name = "Chris Sells" , Technology = "All"},
                 new Bloggers { BloggerID = "5" , Name = "John Bristowe" , Technology = "Web"},
                 new Bloggers { BloggerID = "6" , Name = "Todd Anglin " , Technology = "KendoUI"},
                 new Bloggers { BloggerID = "7", Name= "John Papa ", Technology = "XAML"},
                 new Bloggers { BloggerID = "8" , Name = "Glen Block" , Technology = "REST"},
                 new Bloggers { BloggerID = "9" , Name = "Lohith " , Technology = "Telerik"},
                 new Bloggers { BloggerID = "10" , Name = "Scott Hanselman " , Technology = "All"},
                 new Bloggers { BloggerID = "11" , Name = "Debugmode" , Technology = "Kendo"},
                 new Bloggers { BloggerID = "12" , Name = "Pinal Dave " , Technology = "SQL Server"},
                 new Bloggers { BloggerID = "12" , Name = "Julie Lerman" , Technology = "Entity Framework"} 
             };
            return lstBloggers;
        }



Like This We can able to call Controller Function and retrieve data.
Thank You.

Comments

Popular posts from this blog

The MVC Programming Model Basic

How to User Remember Me on Login By HTTPCookie