MVC – Retrieving data using jQuery and Ajax

Retrieving text using MVC through jQuery and Ajax is fairly simple. What I wanted to happen was to have a link that loaded a DIV when the user clicked it. So the really simple HTML:

<a href="#" onclick="load()">Support</a>

The jQuery for this request wasn’t much, either. Just a simple GET request pointing to the controller and action:

    function load() {
        $.ajax({
            type: 'GET',
            url: '@Url.Content("~/Home/Test")',
            success: function (data) {
                $('#results').text(data);
            }, error: function (xhr) {
                alert(xhr.statusText);
            }
        });
    }

And the Home controller, Test action:

public string Test() {
       return "Testing";
}

I did run into a problem where I was getting “404 Not Found” errors when I attempted to access the action. This was happening because my action was declared as private, so the 404 message made perfect sense.

Advertisements

, , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: