Use ajax with Actionlink

Asked

Viewed 3,565 times

6

I want to change the ActionLink and the URL to work with Ajax, but I don’t know how to do it. Follow my code with ActionLink and URL.

<ul class="nav" id="side-menu">
    <li>
        <a href="#"><i class="fa fa-shopping-cart fa-fw"></i> Pedidos<span class="fa arrow"></span></a>
        <ul class="nav nav-second-level">
            <li>
                @Html.ActionLink("Ver Pedidos", "Index", "Pedido")
            </li>
            <li>
                @Html.ActionLink("Status Pedidos", "Status", "Pedido")
            </li>
        </ul>
    </li>
    <li>
        <a href="@Url.Action("Index","Cliente")"><i class="fa fa-users fa-fw"></i> Clientes</a>
    </li>
    <li>
        <a href="@Url.Action("Index","Carrossel")"><i class="fa fa-picture-o fa-fw"></i> Carrossel</a>
    </li>
    <li>
        <a href="@Url.Action("Index", "Carta")"><i class="fa fa-envelope fa-fw"></i> Cartas</a>
    </li>
    <li>
        <a href="@Url.Action("Index","Usuario")"><i class="fa fa-user fa-fw"></i> Usuários</a>
    </li>
    <li>
        <a href="@Url.Action("Logout")"><i class="fa fa-power-off fa-fw"></i> Logout</a>
    </li>
</ul>
<div id="conteudo"></div>

3 answers

6


Download and put in your project the jQuery and jQuery Unobtrusive Ajax (by Nuget) or Package Manage Consoler.

PM> Install-Package Microsoft.jQuery.Unobtrusive.Ajax -Version 3.1.2

Controller

This controller will work like this: a Index will be the page with the links Ajax.Actionlink and the People will be the Partialview which will be loaded at the time of the click.

public class DefaultController : Controller
{
    private readonly ModelDb db;
    public DefaultController()
    {
        db = new ModelDb();
    }
    // GET: Default
    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public PartialViewResult Pessoas()
    {
        return PartialView(db.Pessoas.OrderBy(x => x.Nome).AsEnumerable());
    }
}

View: Index

@{ Layout = null; }
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</head>
<body>
    <div> 
     @Ajax.ActionLink("Carregar Pessoas", "Pessoas", new AjaxOptions()
     {
       HttpMethod="get", 
       UpdateTargetId="Conteudo", 
       InsertionMode=InsertionMode.Replace, 
       Url="/Default/Pessoas"
     })

     @*Ou Assim*@

     @Ajax.ActionLink("Carregar Pessoas", "Pessoas", "Default", null, new AjaxOptions()
     {
       HttpMethod="get",
       UpdateTargetId="Conteudo",
       InsertionMode=InsertionMode.Replace        
     })
    </div>
    <div id="Conteudo"></div>
</body>
</html>

Ajaxoptions

  • Httpmethod: can be Get, Post, etc.

  • Updatetargetid: place the div that will receive the contents produced by the request Ajax.

  • Insertionmode: place Replace, to always update your div.

  • Url: your Controler and its Actionresult

Note: it has more configurations, but, these are the trivial ones for the operation

View: Partial Pessoas

@model IEnumerable<WebApp.Models.Pessoas>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Nome)
        </th>        
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Nome)
        </td>        
    </tr>
}
</table>

Page Index Rendered

inserir a descrição da imagem aqui

By clicking on the link:

inserir a descrição da imagem aqui

What Ajax.Actionlink generates:

<a data-ajax="true" data-ajax-method="get" data-ajax-mode="replace" data-ajax-update="#Conteudo" href="/Default/Pessoas">Carregar Pessoas</a>

With Jquery

<a onclick="Open('/Default/Pessoas');" href="javascript:void(null);">
            <i class="fa fa-power-off fa-fw"></i> Logout
</a> 

<script>
    function Open(url) {
        $("#Conteudo").load(url);
    }
    $(document).ready({

    });
</script>
  • Could I remove the URL, and put it like this? @Ajax.Actionlink("Upload People", "People", "Controller, new...

  • @Diegozanardo, can yes, there are several overloads this method so can suit in this way that will have the same result, I made an edition with such doubt.

  • i can generate something like this (so that <i> is kept: <a href="@Url.Action("Logout")"><i class="fa fa-power-off fa-Fw"></i> Logout</a>

  • @Diegozanardo, use in this case jQuery, with is in the edited answer. I also have these links, so I prefer to use purely jQuery.

1

Create an id for your Actionlink with jquery search for id can post/get

<ul class="nav" id="side-menu">
    <li>
        <a href="#"><i class="fa fa-shopping-cart fa-fw"></i> Pedidos<span class="fa arrow"></span></a>
        <ul class="nav nav-second-level">
            <li>
             @* cria o id para ActionLink *@
               @Html.ActionLink("Ver Pedidos", "Index", "Pedido",new { id ="idPedido" })
            </li>
            <li>
                @Html.ActionLink("Status Pedidos", "Status", "Pedido")
            </li>
        </ul>
    </li>
    <li>
        <a href="@Url.Action("Index","Cliente")"><i class="fa fa-users fa-fw"></i> Clientes</a>
    </li>
    <li>
        <a href="@Url.Action("Index","Carrossel")"><i class="fa fa-picture-o fa-fw"></i> Carrossel</a>
    </li>
    <li>
        <a href="@Url.Action("Index", "Carta")"><i class="fa fa-envelope fa-fw"></i> Cartas</a>
    </li>
    <li>
        <a href="@Url.Action("Index","Usuario")"><i class="fa fa-user fa-fw"></i> Usuários</a>
    </li>
    <li>
        <a href="@Url.Action("Logout")"><i class="fa fa-power-off fa-fw"></i> Logout</a>
    </li>
</ul>
<div id="conteudo"></div>   

  <script>
     $(function () {
         $('#idPedido').click(function() {
               $.post('seuController', function(retorno) {
                      $('#conteudo').html(retorno);
                  });
          });
      })                                    
  </script>

0

Here’s an example I use on my site:

Razor

@page.Html.DropDownList("UF", page.ViewBag.Estados as SelectList, new { onchange = "vmCadInicial.GetCidades(this.value)")

Javascript

this.GetCidades = function (uf, callback) {
     $.getJSON("/site/apiCidades/AccountMVVM/GetCidades/" + uf + "?callback=?")
           .success(function (data) {
                        if (callback) callback(data);
           })
          .complete(function (jqXhr, textStatus, error) { })
          .error(function (jqXhr, textStatus, error) { });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.