2009-05-17 15 views
9

Estoy tratando de actualizar un <div> en mi vista cuando el usuario hace clic en un Ajax.ActionLink. Sin embargo, siempre navega por toda la página en lugar de insertar la respuesta del servidor en el elemento que especifico.¿Cómo hago que Ajax.ActionLink actualice un elemento en lugar de navegar por toda la página?

Siento que estoy haciendo todo en this example, pero incluso después de crear el caso de prueba más simple todavía no puedo crear el comportamiento que quiero.

En el caso de prueba que sigue, cargar /Company/test y después de hacer clic en "Go!", Me espera la <div> que ser sustituido por "Todo hecho", sino que toda la página se desplaza a /Company/test_ajax.

Estoy seguro de que me falta algo aquí. Gracias por adelantado.

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> 

Respuesta

3

Su ejemplo funciona como se espera en mi computadora. Compruebe si los archivos MicrosoftAjax.js y MicrosoftMvcAjax.js están realmente presentes en la carpeta ../../Scripts.

+0

Estoy bastante seguro de que este era mi problema. Tuve problemas para obtener las fuentes correctas para los scripts y estilos a menos que use la sintaxis Url.Content ("~/project/path/script.js"). –

+5

Para uso MVC3 y superior "jquery.unobtrusive-ajax.js" – RickAndMSFT

1

tuve que modificar los AjaxOptions en mi llamada ActionLink para que funcione:

<%= Ajax.ActionLink("Update", "UpdateContent", new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "target", InsertionMode = InsertionMode.Replace })%> 
+0

esto no funcionó para mí: <% = Ajax.ActionLink ("! Go", "test_ajax", nuevos AjaxOptions() {HTTPMethod = "post", UpdateTargetId = "viewport", InsertionMode = InsertionMode.Replace})%> –

5

Si está utilizando MVC 3 tendrá que incluir "jquery.unobtrusive-ajax.js" como referencia. Ya debería estar presente en su carpeta de Scripts. \ m/

+1

Esta es la respuesta correcta para MVC 3+ – RickAndMSFT

4

He encontrado que agregar jquery.unobtrusive-ajax.js a mi página layout.cshtml evita todo tipo de estupidez "¿por qué esto no funciona?" momentos cuando se trabaja con objetos/métodos ajax.

1

Tuvimos un problema con esto también. Estoy usando VS2013 y jquery-1.10.2.min.js. Tuve que usar una combinación de 4 archivos js para que funcione. Espero que este código de muestra ayude a alguien.

Test.cshtml:

@{ 
    Layout = null; 
} 

<!DOCTYPE html> 

<html> 
<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>test</title> 

     <script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")" type="text/javascript"></script> 
     <script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script> 
     <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script> 
     <script src="@Url.Content("~/Scripts/jquery.history.js")" type="text/javascript"></script> 


    <script type="text/javascript"> 

     $(function() { 
      $.history.init(function (hash) { 
       if (hash.length > 0) { 
        $("#" + hash).click(); 
       } 
      }, 
      { unescape: ",/" }); 
     }); 

     function AddHashTag(hashTag) { 
      window.location.hash = hashTag; 
     } 

    </script> 

</head> 
<body> 
      @Ajax.ActionLink("Render Circle", "GetCircle", null, 
       new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "divContent", OnSuccess = "AddHashTag('circle')" }, 
       new { @id = "circle" }) 

      @Ajax.ActionLink("Render Diamond", "GetDiamond", null, 
       new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "divContent", OnSuccess = "AddHashTag('diamond')" }, 
       new { @id = "diamond" }) 

      @Ajax.ActionLink("Render Star", "GetStar", null, 
       new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "divContent", OnSuccess = "AddHashTag('star')" }, 
       new { @id = "star" }) 

     <div id="divContent" style="width: 300px; height: 300px; text-align: center; vertical-align: middle; 
    margin: 50px 50px;"> 
     </div> 
</body> 
</html> 


star.cshtml: 
star<div class="star"></div> 

diamond.cshtml: 
diamond<div class="diamond"></div> 

circle.cshtml: 
circle<div class="circle"></div> 


Home Controller: 

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

     [HttpGet] 
     public ActionResult GetCircle() 
     { 
      return PartialView("Circle"); 
     } 

     [HttpGet] 
     public ActionResult GetDiamond() 
     { 
      return PartialView("Diamond"); 
     } 

     [HttpGet] 
     public ActionResult GetStar() 
     { 
      return PartialView("Star"); 
     } 
+0

Este debería tener más pulgares arriba, ¡resolvió mi problema! Sin embargo, solo necesitaba estos 2: @ Scripts.Render ("~/Scripts/jquery-1.10.2.min.js") @ Scripts.Render ("~/Scripts/jquery.unobtrusive-ajax.js") –

Cuestiones relacionadas