Mikkel
Mikkel

Reputation: 1811

Using Jquery ajax to call ActionResult method in Controller and return data

I'm trying to understand how the Jquery Ajax methods works. Right now, I have some problems calling the ActionResult method in the controller that will return a PartialView.

Have created an button which I will use to get new data in from the server (Ajax call should run)

Code: (ActionResult in Home controller)

public ActionResult All()
    {
        List<Student> model = db.Students.ToList();

        return PartialView("_Student", model);
    }

This method is the one I'm trying to call when I press the button in the main Index view.

Code: (Index view)

<div class="row">
<div class="small-12 column sbw-travel">
    <h2>Travel</h2>

    <div class="row">
        <div class="small-12 columns">
            <button id="button1" class="sbw-travel-button">Search</button>
        </div>
    </div>

    <div class="small-12 sbw-travel-box" id="rooms">

    </div>
</div>
</div>

When the user hit the button, an Ajax call should run, and the list will appear in the section with id=rooms.

Script: (Ajax code)

 $(document).ready(function () {
    $('#button1').click(function () {
        $.ajax({
            type: 'GET',
            url: @Url.Action("All", "Home"),
            datatype: "html",
            success: function () { 
                $('#rooms').html(???);
            }
        });
        return false;
    });
});

Can any of you see if I have forgot something to make this run like I have described?

Upvotes: 0

Views: 27634

Answers (2)

hughjidette
hughjidette

Reputation: 136

I would suggest loading firebug when you click the button (enable the console), make sure the requested URI is responding with valid HTML data on the click event.

I also generally find using something like:

$('#button1').on('click', function () { ... 

usually yields better results, see here: Difference between .on('click') vs .click()

Upvotes: 0

P. Frank
P. Frank

Reputation: 5745

The result is on the succes event. Try:

$(document).ready(function () {
$('#button1').click(function () {
    $.ajax({
        type: 'GET',
        url: @Url.Action("All", "Home"),
        datatype: "html",
        success: function (data) { 
            $('#rooms').html(data);
        }
    });
    return false;
}); });

Upvotes: 7

Related Questions