I'm basically new to jQuery and AJAX, so I've been trying to imitate a video of someone using jQuery and AJAX in an ASP.NET MVC3 site.
I've got a model called Post which I am trying to display
public class Post
{
public int PostId { get; set; }
public int UserId { get; set; }
public string Body { get; set; }
public DateTime DateCreated { get; set; }
public string Name { get; set; }
}
This is the ActionResult function in my Controller
public ActionResult GetPosts()
{
var posts = blogRepository.GetPosts();
return Json(posts, JsonRequestBehavior.AllowGet);
}
And this is my query method GetPosts:
public List<Post> GetPosts()
{
return (from p in db.Posts
orderby p.DateCreated descending
select p).ToList();
}
Finally, the code in my View with the script that is causing the error I posted in the title:
<table>
<thead>
<tr>
<th>Name</th>
<th>Body</th>
<th>Date</th>
</tr>
</thead>
<tbody id="blogTableBody">
</tbody>
</table>
<script id="blogTemplate" type="text/x-jquery-tmpl">
<tr>
<td>${Name}</td>
<td>${Body}</td>
<td>${DateCreated}</td>
</tr>
</sc开发者_如何学JAVAript>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '/blog/getposts',
type: 'GET',
success: function (result) {
$('#blogTemplate').tmpl(result).appendTo('#blogTableBody');
}
});
});
</script>`
Basically, all I want is to show the post's Name, Body, and DateCreated in a list format in my view. So what am I doing wrong and how can I fix it?
Normally this should work. Here's a complete example (the repository call has been replaced by hardcoded values to simplify and further isolate any problems):
Model:
public class Post
{
public int PostId { get; set; }
public int UserId { get; set; }
public string Body { get; set; }
public DateTime DateCreated { get; set; }
public string Name { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetPosts()
{
var posts = Enumerable.Range(1, 5).Select(x => new Post
{
PostId = x,
UserId = x,
Body = "body " + x,
DateCreated = DateTime.Now,
Name = "name " + x
});
return Json(posts, JsonRequestBehavior.AllowGet);
}
}
View (~/Views/Home/Index.cshtml
):
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
<table>
<thead>
<tr>
<th>Name</th>
<th>Body</th>
<th>Date</th>
</tr>
</thead>
<tbody id="blogTableBody">
</tbody>
</table>
<script id="blogTemplate" type="text/x-jquery-tmpl">
<tr>
<td>${Name}</td>
<td>${Body}</td>
<td>${DateCreated}</td>
</tr>
</script>
<script type="text/javascript">
$(function () {
$.ajax({
url: '/home/getposts',
type: 'GET',
success: function (result) {
$('#blogTemplate').tmpl(result).appendTo('#blogTableBody');
}
});
});
</script>
Note that in my example I have used a beta version of the jquery templates hosted on Microsoft CDN which has some issues with date formats.
精彩评论