I have got this method in my controller.
public string GetTime(string zone)
{
DateTime time = DateTime.UtcNow.AddHours(offsets[zone]);
return string.Format("<div>The time in {0} is {1:h:MM:ss tt}</div>", zone.ToUpper(), time);
}
private Dictionary<string, int> offsets = new Dictionary<string, int> { { "utc", 0 }, { "bst", 1 }, { "mdt", -6 }};
This is my html:
@{
ViewBag.Title = "Statistics";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<html>
<head runat="server">
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")"
type="text/javascript"></script>
</head>
<body>
<h2>
Statistics</h2>
<h2>
What time is it?</h2>
<p>
Show me the time in:<br />
@Ajax.ActionLink("UTC", "GetTime", new { zone = "utc" }, new AjaxOptions { UpdateTargetId = "myResults" })<br />
@Ajax.ActionLink("BST", "GetTime", new { zone = "bst" }, new AjaxOptions { UpdateTargetId = "myResults" })
<br />
@Ajax.ActionLink("MDT", "GetTime", new { zone = "mdt" }, new AjaxOptions { UpdateTargetId = "myResults" })
<br />
</p>
<div id="myResults" style="border: 2px dotted red; padding: .5em;">
Results will appear here
</div>
<p>
This page was generated at @DateTime.UtcNow.ToString("h:MM:ss tt") (UTC)
</p>
</body>
</html>
The problem is that the time doesnt appear in the div element..but the time presented on a blank page (meaning there is a postback instead of an ajax call). Why does that happen?
This is how the html of the links loaded look like:
<script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
You have included a Layout but in your view, you have an entire
<html>document and I suppose that you end up with some very broken HTML at the end.Here’s how your view could look like if you don’t want to use a layout:
The only scripts you need is
jqueryandjquery.unobtrusive-ajax. Also don’t use anyrunat="server"attributes in razor.and if you want to use the layout:
Once again don’t forget the 2 scripts in your layout.
And a final remark: by convention all controller actions should return ActionResults, so:
Finally make sure you don’t use any
Microsoft*.jsscript in your pages. Those are obsolete.