Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make Ajax.ActionLink update an element instead of navigating the whole page?

I am trying to update a <div> in my view when the user clicks on an Ajax.ActionLink. However, it always navigates the entire page rather than inserting the server's response into the element I specify.

I feel like I'm doing everything in this example, but even after creating the simplest test case I still can't create the behavior I want.

In the test case that follows, I load /Company/test and after clicking on "Go!", I expected the <div> to be replaced with "All done", but instead the whole page navigates to /Company/test_ajax.

I'm sure I'm missing something here. Thanks in advance.

CompanyController

public ActionResult test()
{
    return View();
}

public ActionResult test_ajax()
{
    return Content("All done");
}

test.aspx

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
</head>
<body>

<h2>test</h2>
<%= Ajax.ActionLink("Go!", "test_ajax",
    new AjaxOptions {
        UpdateTargetId="viewport"
        }) %>
<div id="viewport">Replace me!</div>

</body></html>
like image 330
Stephen Jennings Avatar asked May 17 '09 08:05

Stephen Jennings


2 Answers

If You are using MVC 3 you will have to include "jquery.unobtrusive-ajax.js" as a reference. It should already be present in your Scripts folder. \m/

like image 162
Vadois Avatar answered Oct 22 '22 09:10

Vadois


I have found that adding jquery.unobtrusive-ajax.js to my layout.cshtml page avoids all sorts of stupid "why does this not work?" moments when working with ajax objects/methods.

like image 35
roblem Avatar answered Oct 22 '22 10:10

roblem