[英]C# code for HTML Next item button
这是我在 asp.net mvc 上的示例博客。 我的问题是如何以及在何处添加 c# 代码,以便 NEWEST 和 OLDER 按钮可以更改为下一篇文章和上一篇文章?
您可以扩展您的 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" })
这是使用jQuery $.getJSON
方法的完整示例,希望对您$.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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.