簡體   English   中英

HTML 下一項按鈕的 C# 代碼

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM