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
By clicking on the link:
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...
– Diego Zanardo
@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.
– user6026
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>
– Diego Zanardo
@Diegozanardo, use in this case jQuery, with is in the edited answer. I also have these links, so I prefer to use purely jQuery.
– user6026