这是我在asp.net mvc上的示例博客。我的问题是如何以及在何处添加c#代码,以便NEWEST和OLDER按钮可以更改为下一篇文章和上一篇文章?
答案 0 :(得分:1)
您可以扩展viewModel以保存下一个和上一个帖子ID,并在SinglePost操作中设置它们。 您的ViewModel可能如下所示:
public class SinglePostViewModel
{
public int OlderId { get; set; }
public int NewerId { get; set; }
}
并在视图中使用它
@Html.ActionLink("Older", "SinglePost",new {Id = Model.OlderId}, new { @class = "btn btn-default" })
@Html.ActionLink("Newer", "SinglePost",new {Id = Model.NewerId}, new { @class = "btn btn-default" })
答案 1 :(得分:1)
以下是使用jQuery $.getJSON
方法的完整示例,希望它可以帮助您:
<强>型号:强>
public class Article
{
public int ID { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
<强>控制器:强>
public class ArticlesController : Controller
{
List<Article> articles = new List<Article>()
{
new Article{ ID=1,Title="Article 1",Body="This is article 1..."},
new Article{ ID=2,Title="Article 2",Body="This is article 2..."},
new Article{ ID=3,Title="Article 3",Body="This is article 3..."}
};
public ActionResult Index()
{
Article article = articles.First();
return View(article);
}
public JsonResult GoToPost(int id,string type)
{
int originalId = id;
int newId = type == "Previous" ? --id : ++id;
Article article = articles.FirstOrDefault(e=>e.ID == newId);
if(article == null)
article = articles.FirstOrDefault(e => e.ID == originalId);
return Json(article, JsonRequestBehavior.AllowGet);
}
}
查看:强>
@model MVCTutorial.Models.Article
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var id = @Model.ID;
$(".nav").click(function () {
var type = $(this).val();
$("#title").empty();
$("#body").empty();
var url = "/Articles/GoToPost?id=" + id + "&type=" + type;
$.getJSON(url, function (data) {
$("#title").append(data.Title);
$("#body").append(data.Body);
id = data.ID;
});
});
});
</script>
<input class="nav" type="button" value="Previous" />
<input class="nav" type="button" value="Next" />
<div id="title">@Model.Title</div>
<hr />
<div id="body">@Model.Body</div>