Reputation: 8684
I wanted to have a hyperlink which when clicked opens in same page without the complete page being refreshed instead of opening different link. In my controller I have following function
public ActionResult PrivacyPolicy()
{
if (Request.IsAjaxRequest())
{
return PartialView();
}
return View();
}
when i run the the program and insert a break point at return view();
I realise that my program always returns view()
instead of PartialView();
here is the index.cshtml
code
@section head{
<script type="text/javascript"
src="@Url.Content("~/scripts/AjaxDemo.js")"></script>
}
@Html.ActionLink("Show the Privacy Policy", "PrivacyPolicy", null, new{id="privacyLink"})
<div id="privacy"></div>
in the partial view PrivacyPolicy I just have few texts.
and the AjaxDemo.js
looks like this
$(document).ready(function () {
$('#privacyLink').click(function (event) {
event.preventDefault();
var url = $(this).attr('href');
$('#privacy').load(url);
});
});
why doesn't my program return partial view? or why is it not taking the ajax request? Shouldn't my program open the link in same index page(CustomAjax), if the javascript in my browser is enables?
Upvotes: 1
Views: 2689
Reputation: 1038930
IIRC event
is a reserved word. Try like this:
$('#privacyLink').click(function (e) {
e.preventDefault();
var url = $(this).attr('href');
$('#privacy').load(url);
});
or:
$('#privacyLink').click(function () {
var url = $(this).attr('href');
$('#privacy').load(url);
return false;
});
Also don't forget to include jQuery.js before your AjaxDemo.js
script.
Upvotes: 0
Reputation: 28737
if you do a jQuery load, it will actually execute a normal request and then load the resulting data inside the given element.
You should remove the custom JavaScript code, use the built-in ajax helpers and specify the updateTargetID in the AjaxOptions:
@Ajax.ActionLink("Show the Privacy Policy", "PrivacyPolicy", null, new{id="privacyLink"}, new AjaxOptions {UpdateTargetId = "privacy"})
<div id="privacy"></div>
EDIT: Adding some more information about IsAjaxRequest():
When you make an Ajax request you're supposed to set the X-Requested-With
HTTP header to XMLHttpRequest'. Internally,
IsAjaxRequest` checks for the presence of this header.
When you use jQuery.Ajax
or the default Ajax-helpers for that matter, this header will be included.
If you use jQuery.load()
this header is not included. jQuery.load does not allow for custom headers to be set.
Edit In order to use Ajax.ActionLink you need to include the unobtrusive ajax library and enable it in the web.config:
<configuration>
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
</configuration>
In addition to setting the flag, you will also need to include the MVC plugin for unobtrusive Ajax with jQuery (~/Scripts/jquery.unobtrusive-ajax.js
).
Upvotes: 2