Jestem w zasadzie nowy w jQuery i AJAX, więc próbowałem naśladować wideo kogoś, kto używa jQuery i AJAX na stronie ASP.NET MVC3.
Mam model o nazwie Post, który próbuję wyświetlić
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; }
}
To jest funkcja ActionResult w moim kontrolerze
public ActionResult GetPosts()
{
var posts = blogRepository.GetPosts();
return Json(posts, JsonRequestBehavior.AllowGet);
}
Oto moja metoda zapytania GetPosts:
public List<Post> GetPosts()
{
return (from p in db.Posts
orderby p.DateCreated descending
select p).ToList();
}
Na koniec kod w moim widoku ze skryptem, który powoduje błąd, który opublikowałem w tytule:
<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">
$(document).ready(function () {
$.ajax({
url: "/blog/getposts",
type: "GET",
success: function (result) {
$("#blogTemplate").tmpl(result).appendTo("#blogTableBody");
}
});
});
</script>`
Zasadniczo wszystko, czego chcę, to pokazać w moim widoku nazwę, treść i datę utworzenia wpisu w formie listy. Więc co robię źle i jak mogę to naprawić?
Odpowiedzi:
0 dla odpowiedzi № 1Normalnie powinno to działać. Oto kompletny przykład (wywołanie repozytorium zostało zastąpione zakodowanymi wartościami w celu uproszczenia i dalszego odizolowania wszelkich problemów):
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; }
}
Kontroler:
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);
}
}
Zobacz (~/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>
Zauważ, że w moim przykładzie użyłem wersji beta szablony jquery hostowany na Microsoft CDN, który ma kilka problemy z formatami dat.