0

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>

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I put a break point on the controller method and it was being called, there was just no result. I used the overloaded method with the JsonRequestBehavior.AllowGet and it worked fine :) Thanks for the help @LukLed
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.