I am trying to make a MVC website with Ajax call. I have no problem using directly jquery, but when i use @Ajax.ActionLink, i don't get the result i want. Here is my view:
<script type="text/javascript">
function deleteComment(id) {
$.post(
"/Role/AjaxTest",
//{ id: id },
function (data) {
$("#testtarget").html(data);
});
}
</script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<h2>TITLE</h2>
<p>
@Ajax.ActionLink("Ajax Test", "AjaxTest", "Role", new AjaxOptions{UpdateTargetId="testtarget",HttpMethod = "Get" , InsertionMode = InsertionMode.Replace })
</p>
<table>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.RoleName)
</td>
<td>
<a onclick="deleteComment('@item.RoleId'); return false;" href="#">Delete</a>
@Html.ActionLink("Delete", "Delete", new { id=item.RoleId })
</td>
</tr>
}
</table>
<div id="testtarget">Test Div</div>
and here is my Controler data:
public string AjaxTest()
{
return "Some random text";
}
My Call on Jquery works perfectly and text appears in the div, but my actionlink just redirects me to : localhost/Role/AjaxTest so i just have the message in a bank browser.
Any idea what's wrong here?
Thanks a lot in advance!
Make sure you have added the jquery.unobtrusive-ajax.js
script to your page:
<script type="text/javascript" src="~/scripts/jquery.unobtrusive-ajax.js"></script>
or if you are using bundles (which is the recommended approach) make sure that you have included a bundle containing this script. For example when you create a new ASP.NET MVC 4 project using the Internet Template that would be the ~/bundles/jqueryval
bundle:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*")
);
So make sure it is included in your view after the jquery bundle:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
Or just combine them into a single bundle. It will all depend on your requirements and whether you need unobtrusive jquery validation support or not.
I would also recommend you to have your controller action return ActionResult and not string:
public ActionResult AjaxTest()
{
return Content("Some random text");
}