简体   繁体   中英

C# code for HTML Next item button

示例图片

This is my example blog on asp.net mvc. My question is how and where to add c# code such that the NEWEST and the OLDER buttons can change to next post and to previous post ?

You could extend your viewModel to hold next and previous post ids and set them in the SinglePost action. Your ViewModel could look like:

public class SinglePostViewModel
{
    public int OlderId { get; set; }
    public int NewerId { get; set; }
}

And use it in the view

@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" })

Here's a complete example using jQuery $.getJSON method, hope it helps you:

Model:

public class Article
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
}

Controller:

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);
        }
    }

View:

@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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM