Khushi
Khushi

Reputation: 1051

How to use ajax in mvc?

I am a very beginner to mvc and ajax both.

I have tried many examples on net but I don't understand how ajax is used practically?

I have a controller named members which has GetAllMembers Method. GetAllMembers returns a List<Members>

Now I want to use JQuery and ajax something like :

 $(document).click(function () {
        $.ajax({
            url: "Members/GetAllMembers",
            success: function () {

            },
            error: function () {
                alert("Failed to get the members");
            }
        });
    });

Is my URL right?

Upon success I want to display that List in a ListBox. How can I get it? Can anyone give me a start?

Upvotes: 0

Views: 150

Answers (3)

PabloWeb18
PabloWeb18

Reputation: 411

Follow this example:

suppose you have this html:

<p>List Box - Single Select<br>
<select id="listBox" name="listbox">

</select>
</p>

So we have this js:

var template = '<option value="$value">$name</option>';

var getAllMembers = function() {
$.ajax({
 url: 'Members/GetAllMembers',
 dataType: 'json', //Assuming Members/GetAllMembers returns a json
 success: function(response) {
  $.each(response, function(index){
   var option = template.replace(/\$value/g, this.value)
                        .replace(/\$name/g, this.name);
   $('#listBox').append(option);
  });
 }
});
};

EDIT: Now you only need to call getAllMembers(); function.

Hope this help.

Pablo.

Upvotes: 1

Nibin
Nibin

Reputation: 3960

 $.ajax({
                type: "POST",
                url: "Members/GetAllMembers", //Your required php page
                data: "id="+ data, //pass your required data here
                success: function(response){  //You obtain the response that you echo from your controller
                    $('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page.
                },
               error: function () {
                   alert("Failed to get the members");
               }
            });

Hope this will help you.. :)

Upvotes: 1

Jeet Bhatt
Jeet Bhatt

Reputation: 778

$(document).click(function () {
            $.ajax({
                url: "Members/GetAllMembers",
                success: function (result) {
    // do your code here
                },
                error: function () {
                    alert("Failed to get the members");
                }
            });
        });

So your request give response in "result" variable. So you have to easily manage result variable value in foreach loop and set value in ListBox HTML.

Upvotes: 1

Related Questions