Gaz
Gaz

Reputation: 3915

calling an AJAX method from an ASP.NET MVC 2 view

I want to know how to use Ajax in MVC2. I created an empty project in Visual Studio and added a home controller under Controllers/Home/HomeController.cs with the following code

How do I use AJAX to call the AjaxTest method on the HomeController when the button is clicked and display that text instead?

public class HomeController : Controller
{       
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult AjaxTest()
    {
        return Json("Whoever answers this rocks!");
    }
}

I added a view under Views/Home/Index.cs with the following code

    <script type="text/javascript">
        function sayHello() {
            alert("hello stackoverflow :)")
        }
    </script>

    <div>
        Hello
        <button onclick="sayHello();"> Click Me! </button>
    </div>

Upvotes: 0

Views: 728

Answers (2)

LukLed
LukLed

Reputation: 31842

This should work:

<script type="text/javascript">
    function sayHello() {
        $.get('/Home/AjaxTest', function(data) { alert(data) });
    }
</script>

Remember to include jQuery in head section of your page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

You can also include jQuery in scripts folder of your project. jQuery is a part of ASP.NET MVC framework files.

EDIT:

Change your action to

public ActionResult AjaxTest()
{
    return Json("Whoever answers this rocks!", JsonRequestBehavior.AllowGet);
}

By default, using Json with get results in "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet." error.

Upvotes: 1

swilliams
swilliams

Reputation: 48920

Don't forget that the <button> element submits the form by default, which may cause unintended effects on your AJAX calls. Consider <input type="button" value="Click Me" /> or returning false in your sayHello() function.

Upvotes: 0

Related Questions